0

I'm building a blog theme. I know that the_date() and date() functions display published date of posts. And I know how to get posts' published time with the_time() function.

I want today's posts to show published time and all other old posts to show published date. For example, today is September 8. All the posts that were published today should show published time (08:40, 16:30, etc). But the posts that were published yesterday or longer before should show only date (September 07, July 26, etc).

How can I achieve this goal?

I guess there's a way to compare post's published date with today's date and make decision whether to display time or date that way. But there must be more optimal and easier way.

  • 1
    without comparing how will you know? – inarilo Sep 8 '17 at 16:11
1
    $post_date = get_the_date('d/m/Y');
    $today = date('d/m/Y');
    if ( $post_date == $today ) {
        echo get_the_date('h:m');
    } else {
        echo get_the_date();
    }
1

This should work for you:

//use inside the loop
$now = time();
$post_date = get_post_time();
if ( $now - $post_date > 3600 * 24 ) {
  $date_format = get_option('date_format');
} else {      
  $date_format = get_option('time_format');
}
$date = date($date_format, $post_date);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.