• Resolved Keith

    (@keithkhl)


    I have below code snippet to show ‘x hours ago’ for the recent posts, and published dates (and time) for older posts.

    —-

    add_filter('get_the_date', 'meks_convert_to_time_ago', 10, 1); //override date display
    add_filter('the_date', 'meks_convert_to_time_ago', 10, 1); //override date display
    add_filter('get_the_time', 'meks_convert_to_time_ago', 10, 1); //override time display
    add_filter('the_time', 'meks_convert_to_time_ago', 10, 1); //override time display

    /* Callback function for post time and date filter hooks */
    function meks_convert_to_time_ago($orig_time) {
    global $post;
    $orig_time = strtotime($post->post_date);
    if (is_front_page() & (time() - $orig_time) < 60*60*24 ) {
    return human_time_diff($orig_time, time()) . ' ' . __('ago');
    }
    else if (is_front_page()) {
    date_default_timezone_set(wp_timezone_string());
    return wp_date('Y-m-d', $orig_time);
    }
    else {
    date_default_timezone_set(wp_timezone_string());
    return wp_date('Y-m-d H:i', $orig_time);
    }
    }

    I apply that code snippet only for front-end. Adding that to backend makes me to see time stamp everywhere in admin, so not needed. It works great, but there is a glitch.

    I live in UMT+5 timezone, but the $orig_time is not aligned to my timezone, if I exclude ‘date_default_timezone_set(wp_timezone_string())’. The problem is that, due to the different timezone, the displayed time for each post is from UMT+5, but the url from frontend page is created based on UMT+0. Real url is created based on UMT+5.

    This may sound a little complex, so let me try to clarify what I have. Say, I have a post published at 00:01 on Jun 1, 2024. By my url structure of /year/month/ , below is the case.

    • Backend URL: example.com/2024/06/post_name
    • Frontend URL: example.com/2024/05/post_name

    Without ‘date_default_timezone_set(wp_timezone_string())’, the frontend URL goes back to backend URL. But, on the frontend, I have post date/time by the standpoint of UMT+0. For example, for the above post, it shows like

    • 05:01, Jun 1, 2024

    I was going to change permalink structure, but /year/month/ is requirement for business purposes.

    I guess I just have to change ‘$orig_time’ value to the right timezone without ‘date_default_timezone_set’ function. Is there any way, or easier way to fix this?

Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)

The topic ‘Time mismatch between frontend and backend’ is closed to new replies.