I have a pre_get_posts filter to show exclude some posts on the homepage. But I can’t exclude the posts which are closed for commenting. How do I do this?

What I have is:

function wp_filter_pre_get_posts( $query ) {
// Only modify when on homepage & only the main query
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'comment_status', 'open' );
        $query->set( 'tag__not_in', '188' );
        $query->set( 'posts_per_page', '3' );
    }
}
add_filter( 'pre_get_posts', 'wp_filter_pre_get_posts' );

Excluding the post from category 188 works fine, but excluding the posts with closed comments does not. Any hints?

1 Answer
1

Because comment_status is not a built-in query argument – but you can easily implement it:

function wpse_214323_query_by_comment_status( $where, $wp_query ) {
    global $wpdb;

    if ( ! empty( $wp_query->query_vars['comment_status'] ) ) {
        $status = $wp_query->query_vars['comment_status'];

        if ( $status !== 'open' )
            $status="closed";

        $where .= " AND $wpdb->posts.comment_status="$status"";
    }

    return $where;
}

add_filter( 'posts_where', 'wpse_214323_query_by_comment_status', 10, 2 );

Use this in addition to your existing code, now you can query 'comment_status' => 'open/closed'

Leave a Reply

Your email address will not be published. Required fields are marked *