Pepe
Pepe

Reputation: 1002

Get "latest comment date" of a Wordpress page in a loop

Is there a simple way to get the "latest comment date" of a wordpress page?

For the page itself there is a simple solution like this:

get_the_date('Y-m-d', $post->ID)

For example this will not work for me (especially since i can't define the last comment either):

get_comment_date( 'Ymd', $post->ID);

And my array way doesnt work. The "comment_count" is fine, but the "get_comment_date( 'd\/m\/Y' )" is always the same date, for all pages - why?

$args = array(
'post_id' => $post->ID,
'posts_per_page' => 10,
'post_type' => 'page',
'orderby'   => 'date',
'category_name' => 'MyName');

$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>

<?php echo '<div class="comments ' . get_comment_date( 'd\/m\/Y' ) . '"><span>'. $comments_count .'<span></div>'; ?>

<?php endforeach; ?>

Upvotes: 1

Views: 500

Answers (1)

Ruvee
Ruvee

Reputation: 9107

If I understood you correctly, you're trying to get the most current comment for a specific page. So, I'd use get_commentsDocs function.

$comment_args = array(
  'post_type' => 'page',
  'post_id'   => get_the_id(), // Or if you're in a page loop, you could use $post->ID instead of get_the_id()
  'number'    => 1,
);

$latest_comment = get_comments($comment_args);

// This would give you the latest comment
print_r($latest_comment[0]->comment_content);

// This would give you the comment date
print_r($latest_comment[0]->comment_date);

// This would give you the comment date in gmt
print_r($latest_comment[0]->comment_date_gmt);

Note that the 'number' => 1, would retrieve the latest comment.


So your entire code with a loop for pages would be something like this:

$args = array(
    'posts_per_page' => 10,
    'post_type'      => 'page',
);

$query = new WP_Query($args);

while ($query->have_posts()) {
    $query->the_post();

    the_title();

    $comment_args = array(
        'post_id'   => get_the_ID(),
        'number'    => 1,
    );

    $latest_comment = get_comments($comment_args);

    ?>
    <div class="comments"><?php echo $latest_comment[0]->comment_date; ?></div>
    <hr>
    <?php
};

wp_reset_postdata();

Here's the results:

enter image description here

Let me know if that's what you were looking for!

Upvotes: 2

Related Questions