0

I try to get all comments of a specific post, but it is not working like the way I do want. I use $assignment->ID to get all comments for a specific page ID. Even when I change $assignment->ID to 101 it is not working and he still shows all the comments of all posts.

foreach($assignments as $assignment) {

    echo $assignment->post_title;
                                
    $args = array(
        'number' => 0,
        'status' => 'approve',
        // shows all comments, but it shouldn't
        'comment_post_ID' => $assignment->ID
    );
                                
    $comments = get_comments( $args );
                                
    if ( $comments ) {
        foreach ( $comments as $comment )   {
            echo '<li>';
            echo $comment->comment_content;
            echo '</li>';
        }
    }

}

I think I miss an important $arg, but I'm not sure which one. It doesn't matter what I do, all comments are showing up everytime..

1 Answer 1

0

Based on developer documents of get_comments functions, it is using args like WP_Comment_Query::__construct Method which is accepts post_id in the argument's array. So, the code will be like:

foreach($assignments as $assignment) {

    echo $assignment->post_title;
                                
    $args = array(
        'number' => 0,
        'status' => 'approve',
        // shows all comments, but it shouldn't
        'post_id' => $assignment->ID
    );
                                
    $comments = get_comments( $args );
                                
    if ( $comments ) {
        foreach ( $comments as $comment )   {
            echo '<li>';
            echo $comment->comment_content;
            echo '</li>';
        }
    }

}

Links:

https://developer.wordpress.org/reference/functions/get_comments/ https://developer.wordpress.org/reference/classes/wp_comment_query/__construct/

2
  • You just beat me. I saw it too. Thanks! Commented Sep 6, 2020 at 19:44
  • Please select the answer as correct if it resolves your problem, so others will use it too. Thanks.
    – Hector
    Commented Sep 6, 2020 at 19:47

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.