By Stephen Walker
Share
I used ChatGPT to generate a shortcode that would indicate whether a business is opened or closed.
Demo: We're closed!
The prompt: Using WordPress, create a shortcode that displays whether a business is open or closed based on an array of days and times.
The Response
Creating a shortcode that displays a company’s business hours involves coding a WordPress shortcode in PHP. Here is a simple example where you set the open and close times for each day of the week.
First, add the following code to your theme’s functions.php
file:
function business_hours_shortcode($atts) {
// Set timezone - change this to match your own.
date_default_timezone_set('America/Los_Angeles');
// An array of your opening hours.
$opening_hours = array(
'Monday' => array('08:00', '17:00'),
'Tuesday' => array('08:00', '17:00'),
'Wednesday' => array('08:00', '17:00'),
'Thursday' => array('08:00', '17:00'),
'Friday' => array('08:00', '17:00'),
'Saturday' => array('08:00', '12:00'),
'Sunday' => array('Closed'),
);
// Get current day and time.
$current_day = date('l');
$current_time = date('H:i');
// Get today's opening hours.
$today_hours = $opening_hours[$current_day];
// Check if we have opening hours for today.
if (!isset($today_hours) || count($today_hours) < 2) {
return "We're closed today.";
}
// Check if current time is between opening hours.
if ($current_time >= $today_hours[0] && $current_time <= $today_hours[1]) {
return "We're open!";
} else {
return "We're closed!";
}
}
add_shortcode('business_hours', 'business_hours_shortcode');
Replace the timezone and the hours in the $opening_hours
array to match your business hours. In this example, we’re open from 8:00 AM to 5:00 PM from Monday to Friday, from 8:00 AM to 12:00 PM on Saturday, and closed on Sunday.
Once you have added this code to your theme’s functions.php
file, you can use the We're closed!
shortcode in your posts, pages, or widgets to display whether the business is currently open or closed.
This is a basic example and may not cover all scenarios. For example, it does not handle holidays or special cases when your normal hours may change. For a more comprehensive solution, you may want to consider a business hours plugin that provides more flexibility and features.
Originally published on May 31, 2023