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..
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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/
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0