Skip to content

Learn

Show the Post Author's Current Time

D Donald McGuinn · Feb 8, 2024 · 1 min read
Show the Post Author's Current Time

VIEW DEMO

In order to do this, you need to add the "Timezone" field to that post type. That is required to make it work. Then perform the following:

  1. Install the Voxel Child Theme.
  2. Navigate to Appearance > Theme Editor > functions.php
  3. Add the following snippet under all existing code
  4. Use the shortcode [user_time] to show the time in the post template.
function display_datetime_with_timezone($atts) {
    $atts = shortcode_atts(array('id' => get_the_ID()), $atts);
    $post_id = $atts['id'];
    $timezone = get_post_meta($post_id, 'timezone', true);

    if (empty($timezone) || !in_array($timezone, timezone_identifiers_list())) {
        return 'Invalid or undefined timezone for this post.';
    }

    try {
        $datetimezone = new DateTimeZone($timezone);
        $datetime = new DateTime('now', $datetimezone);
        return $datetime->format('g:i A');
    } catch (Exception $e) {
        return 'Error retrieving date and time: ' . $e->getMessage();
    }
}

add_shortcode('user_time', 'display_datetime_with_timezone');
Voxel Guide assistant
Ask about snippets, addons & how-tos

Hey — how can I help?

I can dig through the library for snippets, addons, and tutorials.

AI can be wrong — double-check anything important.