How to filter comments in a post by a certain comment meta value

I'm trying to make the comments list in wordpress posts so that they will only list comments with a certain meta_key and meta_value. So far, I've tried finding answers on google and only found out how to assign a meta key/value when someone adds a comment in the comments form.

in the theme's functions.php

<?php

add_action( 'comment_post', function($comment_id) {
    add_comment_meta( $comment_id, $my_meta_key, $my_meta_value );
});

Now what I can't figure out is, how do I make the wordpress posts filter the comments so they only list comments with the certain meta key and value I want them to.

I've made my theme using underscores and I list the comments inside comments.php using the wp_list_comments() function.

Upvotes: 3

Views: 2087

Answers (1)

birgire
birgire

Reputation: 11378

Here's an example how to modify the main comment query, in comments_template(), through the comments_template_query_args filter (available for WordPress versions 4.5+):

/**
 * Filter non-threaded comments by comment meta, in the (main) comments template
 */
add_filter( 'comments_template_query_args', function( $comment_args )
{
    // Only modify non-threaded comments
    if(    isset( $comment_args['hierarchical'] ) 
        && 'threaded' === $comment_args['hierarchical'] 
    )
        return $comment_args;

    // Our modifications
    $comment_args['meta_query'] = [
        [
            'key'     => 'some_key',
            'value'   => 'some_value',
            'compare' => '='
        ]
    ];        

    return $comment_args;
} );

where you adjust the meta query to your needs. Note that this example assumes PHP 5.4+.

Upvotes: 4

Related Questions