How can I get a list of comments by target

I’ve been looking at the classes WP_Comment_Query and WP_Meta_Query but to be honest, I can’t figure out how to use them together. I want to query the database for comments where wp_posts::post_author == X and wp_comments::comment_post_id == wp_posts::post_id. Could anybody give an example of usage?

Since SQL is not my thing, and this next question is not really WP related, but how would a SQL query be built to handle 2 tables?

Related posts

1 comment

  1. When it comes to retrieve posts, it’s supposed to call WP_Query.

    WP_Query has an argument called meta_query but it doesn’t have comment_query.

    So it might need a trick to achieve what you want,

    $args = array();
    $args['feed'] = 1;
    $args['withcomments'] = 1;
    $args['author'] = 1; //author id.
    $query = new WP_Query($args);
    $posts = $query->posts;
    //do what you want
    wp_reset_postdata();
    

    Please note that, the $args may need more values such as post_status and posts_per_page. I’m just giving you a general idea here.

    It’ll generate two SQL queries:

    SELECT wp_comments . * 
    FROM wp_comments
    JOIN wp_posts ON ( wp_comments.comment_post_ID = wp_posts.ID ) 
    WHERE comment_approved =  '1'
    AND (
    wp_posts.post_author =1
    )
    AND wp_posts.post_type =  'post'
    AND (
    wp_posts.post_status =  'publish'
    OR wp_posts.post_status =  'private'
    )
    GROUP BY wp_comments.comment_id
    ORDER BY comment_date_gmt DESC 
    
    
    
    SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
    FROM wp_posts
    WHERE 1 =1
    AND wp_posts.ID
    IN ( 528, 1 ) 
    ORDER BY wp_posts.post_date DESC 
    LIMIT 0 , 10
    

    The second SQL query will retrieve posts by posts IDs which returned from 1st SQL.


    I would recommend using custom SQL query for your task

    SELECT wp_posts . * 
    FROM wp_posts
    JOIN wp_comments ON ( wp_comments.comment_post_ID = wp_posts.ID ) 
    WHERE comment_approved =  '1'
    AND (
    wp_posts.post_author =1
    )
    AND wp_posts.post_type =  'post'
    AND wp_posts.post_status =  'publish'
    

Comments are closed.