2

How would I count (and display) the number of times a comment meta field's value is a post's entire comments?

e.g. meta key is "fish" and key value "shark" appears in 5 comments of a post.

1

1 Answer 1

1

You should be able to do a meta_query in a WP_Comment_Query():

$args = array(
    'post_id'    => 'post-id-here',
    'meta_query' => array(
        array(
            'key'     => 'fish',
            'value'   => 'shark',
            'compare' => 'LIKE'
        )
    )
 );

// Query the comments
$comment_query = new WP_Comment_Query( $args );

// Count the number of comments
$count = count ( $comment_query );

The WP_Comment_query() accepts a 'post_id' so you can search withing a specific post's comments.

9
  • How would I echo that?
    – Pete
    Feb 21, 2018 at 9:26
  • What would the argument be for post_idto query the current post comments?
    – Pete
    Feb 21, 2018 at 9:28
  • This is what i have... $args = array( 'post_id' => $post->ID, 'meta_query' => array( array( 'key' => 'joinus', 'value' => 'Yes', 'compare' => 'LIKE' ) ) ); // Query the comments $comment_query = new WP_Comment_Query( $args ); // Count the number of comments $count = count ( $comment_query ); // echo the number of comments echo $count;
    – Pete
    Feb 21, 2018 at 9:32
  • @Pete Are you sure that the $post->ID is set? Where and how are you using this code?
    – Johansson
    Feb 21, 2018 at 9:51
  • I'm using this in my single.php loop - so I guess I need to find the current post ID
    – Pete
    Feb 21, 2018 at 10:10

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.