WordPress Shortcode that Displays Current Time

Add the following code in your theme’s functions.php file or a Code Snippet plugin. Then use the shortcode [current_time] to display the results.

// Function to handle the shortcode
function display_current_time() {
    // Set the timezone if necessary, default is UTC
    // For example, for Eastern Time use 'America/New_York'
    // You can find your timezone in the PHP manual: https://www.php.net/manual/en/timezones.php
    date_default_timezone_set('UTC');

    // Format the time as desired
    // H:i:s = hours:minutes:seconds, add or remove parts as needed
    $time_format = 'H:i:s'; // 24-hour format
    // $time_format = 'h:i:s A'; // 12-hour format with AM/PM
    
    // Get the current time
    $current_time = date($time_format);
    
    // Return the time for the shortcode
    return $current_time;
}

// Add the shortcode [current_time] that will execute the function above
add_shortcode('current_time', 'display_current_time');