Replacing the_modified_date With Date of the Most Recent Comment

Sometimes theres an instance when you want to replace WordPress’ the_modified_date with the date of the most recent comment. I recently needed to do this when I was working on a small, light project tracker plugin for my department at work. In my projects archive there is a list of projects as shown below:

In this case I have comments setup as project updates, so when a team member looks at the table I wanted them to see the last time the project was updated (or a comment was posted). In the code below you will see how I replaced the date that the post itself was last modified with the date of the most recent comment while using the_modified_date as a fall back for projects that had no comments or updates.

You would replace:

<?php the_modified_date( ); ?>

With this:

<?php 
// Get the current post's ID.
$id = get_the_ID();
// Use the above ID to find out how many comments are attached to the post.
$comment_num = get_comments_number( $id );
// If there are more than 0 comments attached, run the comment query.
if ( $comment_num > 0 ) {
  // Force the newest comment into position [0] in the array returned to $comments.
  $comment_query = array(
    'order' => 'DESC',
  );
  $comments = get_comments( $comment_query );
  // Print the date of the most recent comment.
  echo $comments[0]->comment_date;
// Otherwise print the last date that the post was modified.
} else {
  the_modified_date( );
}
?>

this code produces this:

As you can see, the default dates do not look the same, a little bit of code on line 17 that will fix this:

<?php 
// Get the current post's ID.
$id = get_the_ID();
// Use the above ID to find out how many comments are attached to the post.
$comment_num = get_comments_number( $id );
// If there are more than 0 comments attached, run the comment query.
if ( $comment_num > 0 ) {
  // Force the newest comment into position [0] in the array returned to $comments.
  $comment_query = array(
    'order' => 'DESC',
  );
  $comments = get_comments( $comment_query );
  // Print the date of the most recent comment.
  echo $comments[0]->comment_date;
// Otherwise print the last date that the post was modified.
} else {
  the_modified_date( 'Y-m-d H:i:s' );
}
?>

Adding that code will give you this result:

 

Resources:

Leave a Reply

Your email address will not be published. Required fields are marked *