It appears that looping through wp_comment_query() with the argument post_status
set to publish
also lists comments that are posted on password protected posts.
Is this the correct behavior or is this a bug? How can I avoid looping through comments submitted to password protected posts?
I checked through the database wp_comments
table and there doesn’t seem to be a relevant entry to play with.
Using the Query Monitor plugin, I was able to inspect the SQL query:
SELECT *
FROM wp_comments JOIN wp_posts
ON wp_posts.ID = wp_comments.comment_post_ID
WHERE ( comment_approved = '1' )
AND wp_posts.post_status IN ('publish')
AND wp_posts.post_type IN ('post')
ORDER BY wp_comments.comment_date_gmt DESC
LIMIT 8
To clarify the problem, as it stands, if you use wp_comment_query()
to display comments (for example in the front-end), then comments that were posted on password protected posts are looped through.
1 Answer
It’s not a bug (gasp!) really just not provided for. You have to add a filter to do this, eg
add_filter( 'comments_clauses', function ( $pieces, $query ) {
if ( empty( $query->query_vars['wpse_no_password'] ) ) return $pieces;
global $wpdb;
$pieces[ 'where' ] .= $wpdb->prepare( ' AND ' . $wpdb->posts . '.post_password = %s', '' );
return $pieces;
}, 10, 2 );
$args = array( 'post_status' => 'publish', 'wpse_no_password' => 1 );
$query = new WP_Comment_Query( $args );