Kvvaradha
Kvvaradha

Reputation: 852

How to Get Latest Comment of a Post in WordPress?

I have to get the latest comment of a post. I mean, the most recent comment. The Following Code I Tried. But it returns nothing. Its empty.

$args = array(  
    'number' => '1',
    'post_id' => $post->ID
);
$comments = get_comments($args);
echo $comments->comment_content; 

But the post has more than 3 comments.

Upvotes: 2

Views: 4778

Answers (2)

Rohil_PHPBeginner
Rohil_PHPBeginner

Reputation: 6080

Try this :

<?php 
    $args = array(
        'post_id' => $post->ID,
        'orderby' => array('comment_date'),
        'order' => 'DESC',
        'number' => 1
    );
    $comment = get_comments( $args );
    echo $comment[0]->comment_content;
?>

Upvotes: 3

user4094161
user4094161

Reputation:

Try this code:

<?php 
    $args = array(
            'number' => '1',
            'post_id' => $post->ID
    );
    $comments = get_comments($args);
    foreach($comments as $comment) :
        echo $comment->comment_content;
    endforeach;
?>

Upvotes: 1

Related Questions