Last updated for blog post?

Hi there,

I’m trying to display the last updated date at the top of my blog posts. I’m using the code:

function wpb_last_updated_date( $content ) {
$u_time = get_the_time(‘U’);
$u_modified_time = get_the_modified_time(‘U’);
if ($u_modified_time >= $u_time + 86400) {
$updated_date = get_the_modified_time(‘F jS, Y’);
$updated_time = get_the_modified_time(‘h:i a’);
$custom_content .= '

Last updated on ‘. $updated_date . ’ at ‘. $updated_time .’

’;
}

$custom_content .= $content;
return $custom_content;
}
add_filter( ‘the_content’, ‘wpb_last_updated_date’ );

However, it is adding a last updated date to pages AND posts. Do you know what I am missing so it only shows on posts?

Thank you!

Hi @dkolba,

The filter where you add it both works on pages and post. We need to check if it’s post first. Something like this:


function wpb_last_updated_date( $content ) {
  if(is_single()){ /*This will check if it's single post*/

    $u_time = get_the_time('U');
    $u_modified_time = get_the_modified_time('U');

    if ($u_modified_time >= $u_time + 86400) {

      $updated_date = get_the_modified_time('F jS, Y');
      $updated_time = get_the_modified_time('h:i a');
      $custom_content .= 'Last updated on '. $updated_date . ' at '. $updated_time;

    }
    $custom_content .= $content;
    return $custom_content;

  }
}
add_filter( 'the_content', 'wpb_last_updated_date' );

See this: https://developer.wordpress.org/reference/functions/is_single/

Hope this helps.

Thank you. This works, however, it also causes all the content on my pages (home page, landing pages etc) to disappear…the content on my posts, however, if still there. Would you happen to know why it’s doing that and how to stop that from happening?

Thank you.

Hello @dkolba,

When the condition fails, the content should still be returned. Please have the code updated and use this:

function wpb_last_updated_date( $content ) {
  if( is_single() ){ /*This will check if it's single post*/

    $u_time = get_the_time('U');
    $u_modified_time = get_the_modified_time('U');

    if ($u_modified_time >= $u_time + 86400) {

      $updated_date = get_the_modified_time('F jS, Y');
      $updated_time = get_the_modified_time('h:i a');
      $custom_content .= 'Last updated on '. $updated_date . ' at '. $updated_time;

    }
    $custom_content .= $content;
    return $custom_content;

  }
  
  return $content;
}
add_filter( 'the_content', 'wpb_last_updated_date' );

We would love to know if this has worked for you. Thank you.

That worked! Thank you so much!

You’re always welcome!

Cheers.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.