2

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?

2

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'

  • Thank you so much! It works like a charm. If anyone else needs it a little more info: Add the code from TheDeadMedic and add to your wp_filter_pre_get_posts: $query->set( 'comment_status', 'open' ); – benutzerfreund Jan 13 '16 at 17:15
  • One more question: I am trying to add the possibility for exceptions – to show certain posts for which the comments are closed nevertheless. I tried: function wpjj_filter_sticky( $query ) { $meta_query = array( 'relation' => 'OR', array( 'key' => 'show_aways', 'value' => 'yes', 'compare' => 'EXISTS' ), array ( 'comment_status' => 'open' ) ); $query->set( 'meta_query', $meta_query ); } add_filter( 'pre_get_posts', 'wpjj_filter_sticky' ); But it will only show the posts with the meta, not the open posts. – benutzerfreund Jan 21 '16 at 10:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.