Show the Post Author's Current Time
D
Donald McGuinn
·
Feb 8, 2024
·
1 min read
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:
- Install the Voxel Child Theme.
- Navigate to Appearance > Theme Editor > functions.php
- Add the following snippet under all existing code
- 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');