0

How to filter recent comment by post meta value. I have a key “target” in post_meta, and I want to display in my new recent comment widgets.

My code : $comment = get_comments( array( ‘number => $instance[‘number’], ‘meta_query’ => array( ‘meta_key‘ => ‘target’, ‘meta_value’ => array(‘public’) ) );

I think the request value isn’t the post value.

Thx

1 Answer 1

0
$post_args = array(
  'post_type'              => 'post',
  'posts_per_page'         => -1,
  'meta_key'               => 'field_name',
  'meta_value'             => 'field_value',
);

$post_query = new WP_Query( $post_args );
$posts_array= array();
if ( $post_query->have_posts() ) {
    while ( $post_query->have_posts() ) {
        $post_query->the_post();
        $posts_array[] = get_the_ID(); //Array of post ids
    }
    wp_reset_postdata();
}

//YOUR COMMENT ARGS SHOULD BE THIS
$args = array(
    'number'         => '30',
    'order'          => 'DESC',
    'orderby'        => 'comment_date',
    'post__in'        => $posts_array, //THIS IS THE ARRAY OF POST IDS WITH META QUERY
);

$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );

Don't forget to update the test meta key and test meta value by your meta key and meta value.

2
  • I make a pre_get_post action to filter posts with meta_key and meta_value. I works fine for posts, posts widget, but not for comment widget. I try that tomorrow morning anyway. Commented Jul 1, 2020 at 19:13
  • Solution dors not Work 😕 I put a sample of widget here. pastebin.com/Xm1QiCxg Commented Jul 2, 2020 at 8:18

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.