1

I'm looking forward to display, somewhere in the homepage of a WP site, a legend saying:

Last updated: XX/XX

by grabbing the date from the most recent post, but not showing any of its content, just the date.

Is there any quick way to do this?

2 Answers 2

4

I would save an option on post save:

add_action(
  'save_post',
  function($id,$p) {
    if (
      (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) 
      || (defined('DOING_AJAX') && DOING_AJAX)
      || ($p->post_status === 'auto-draft')
    ) {
      return;
    }
    update_option('_last_site_update',$p->post_date);
  },
  1,2
);

And retrieve it with a variant of the function provided by @G-M :

function my_last_updated( $format = '' ) {
  $last = get_option('_last_site_update');
  if ( empty($last) ) return;
  if ( empty($format) ) {
    $format = get_option('date_format');
  }
  return mysql2date($format,$last);
}
echo my_last_updated();

This way you:

  1. push the heavy lifting to the admin side,
  2. eliminate the unnecessary work of a full post query (via wp_get_recent_posts),
  3. replace that heavy query with a very simple get_option query,
  4. and make the whole thing cache-friendly
1
  • 1
    +1 I've started answer saying "There are different way to do this" and this one is a better way.
    – gmazzap
    Commented Nov 10, 2013 at 15:57
1

There are different way to do this.

The easiest, in my opinion is to use wp_get_recent_posts to retrieve the last post and the print the post modified date.

Wrapping it in a function make it flexible and reusable. In your functions.php you can put:

function my_last_updated( $format = '' ) {
  $lasts = wp_get_recent_posts( array('numberposts'=>1, 'post_status'=>'publish') );
  if ( empty($lasts) ) return;
  $last = array_pop($lasts);
  if ( empty($format) ) $format = get_option('date_format');
  return mysql2date( $format, $last['post_modified'] );
}

Then you can use it like so:

<p>Last updated: <?php echo my_last_updated() ?>.</p>

The argument $format let you choose a different date format for the date see here to choose one. If nothing is passed, the format set in WP options is used.

1
  • @RogerW. Yes it works, but answer you accepted is better, I've +1 it. So you have done right choice ;)
    – gmazzap
    Commented Nov 12, 2013 at 7:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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