简体   繁体   中英

Filter wordpress comments by user role

Trying to filter all my comments by a specific user role. In this case, the user role is called group1. This will return all comments only when I remove WHERE m.meta_key = 'wp_capabilities' AND m.meta_value = 'group1' from the query below.

$query = $wpdb->prepare( "
SELECT *
  FROM $wpdb->comments c
  LEFT 
  JOIN $wpdb->commentmeta cm 
    ON c.comment_ID = cm.comment_id
  LEFT 
  JOIN $wpdb->users u 
    ON c.user_id = u.ID
  LEFT 
  JOIN $wpdb->usermeta m 
    ON m.user_id = u.ID
 WHERE c.comment_post_ID = %s
   AND c.comment_approved = 1
 WHERE m.meta_key = 'wp_capabilities'
   AND m.meta_value = 'group1'
 ORDER 
    BY c.comment_ID $comment_order
                    ",
                    $post->ID);

You have two WHERE clauses, but even on fixing the syntax error, it'll work as inner join as the filter conditions for the outer table in the where clause turn an outer join into an inner join.

Add the filters for outer tables in the LEFT JOIN 's ON clause itself:

select *
from $wpdb - > comments c
left join $wpdb - > commentmeta cm on c.comment_ID = cm.comment_id
left join $wpdb - > users u on c.user_id = u.ID
left join $wpdb - > usermeta m on m.user_id = u.ID
    and m.meta_key = 'wp_capabilities'
    and m.meta_value = 'group1'
where c.comment_post_ID = % s
    and c.comment_approved = 1
order by c.comment_ID $comment_order

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM