Custom WP_Query with complex ‘post_status’ argument

I’m trying to run a WP_Query() with a bit of a twist.

I need to include two post_statuses and specifically exclude another.

Read More

I’ve got WP_Query( array( 'post_status' => array( 'publish', 'customstatus' ) ) ); which works, but it seems to also pull in auto-draft, which I can NOT have.

Is there a way to do like

'post_status' => array( array('publish', 'customstatus'), 'not_in' => 'auto-draft' ))

where I can include two and exclude one explicitly?

Related posts

Leave a Reply

1 comment

  1. Things to note:

    It depends on what type of page the query is happening

    If you’re logged in, private post status will be drawn in for example.

    Use a filter

    As the status is something that gets added to the WHERE clause, you have a pretty specific filter that you can use to alter the actual query string.

    apply_filters_ref_array('posts_where', array( $where, &$this ) );
    

    So an actual callback would look close to this general example:

    add_filter( 'posts_where', 'wpse82200_posts_where_status' );
    function wpse82200_posts_where_status( $where, $query )
    {
        // Run only once; Don't intercept later queries
        remove_filter( current_filter(), __FUNCTION__ );
    
        // Do your replace logic here
    
        return $where;
    }
    

    Of course, you should add that filter callback right before the line where you do the query, so nothing gets in between. The example removes itself after firing once.