php - How to count how many posts the user has commented on?
Get the solution ↓↓↓I know how to get the number of all comments written by a specific user, but how to count how many posts the user has commented on (in WordPress).
Answer
Solution:
If you want to count the comments a user made on posts:
You can useget_comments()
function
https://developer.wordpress.org/reference/functions/get_comments/
which accepts an array of arguments
https://developer.wordpress.org/reference/classes/wp_comment_query/__construct/
In your arguments array, you useuser_id
to only get comments of this user. You also usecount
to return the number of comments.
The code looks like this:
<?php
$comments_args = array(
'user_id' => 12, // Your user ID, for example user with id 12
'count' => true // Return count
);
$comments_count = get_comments( $comments_args );
echo $comments_count;
?>
You now have the number of comments the user with id 12 wrote.
If you want to count the posts where the user added one or more comments:
You can useWP_Query
and run through your posts and usewp_list_pluck()
to pluck the field out of each object.
$args = array(
'post_type' => 'post',
'posts_per_page' =>-1,
'post__in' => array_unique(
wp_list_pluck(
get_comments( array(
'user_id' => get_current_user_id()
)
),
'comment_post_ID'
)
),
);
$comment_query = new WP_Query( $args );
// The Loop
$counter = 0;
if ( $comment_query ->have_posts() ) {
while ( $comment_query ->have_posts() ) {
$comment_query ->the_post();
$counter++;
// or display title or something
}
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
}
You can now display the number usingecho $counter;
.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: http failure during parsing for
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.