Can’t get drafts with WP_Query using post_status parameter

I can’t seem to get drafts to show up with WP_Query, even when post_status is set to ‘any’ or ‘draft’

        $args = array(
                    'p' => 1234, 
                    'post_type' => 'any',
                    'post_status' => 'any'
                    );
        $query = new WP_Query( $args );

        while ( $query->have_posts() ) : $query->the_post();
            // display the post
        endwhile;

        wp_reset_postdata();

If I go back and Publish post 1234, WP_Query grabs it just fine. But when it is a draft, neither any nor draft grabs it.

Read More

I read that the exclude_from_search parameter in register_post_type() prevents posts from showing up with WP_Query, so I set it to false in the post_type I am grabbing from, like so:

$args = array(
    'labels' => $labels,
    'description' => '',
    'public' => true,
    'publicly_queryable' => true,
    'exclude_from_search' => false,
    'show_ui' => true,
    'menu_position' => 60,
    'menu_icon' => null,
    'capability_type' => post,
    'hierarchical' => false,
    'supports' => array('title', 'editor', 'author', 'excerpt', 'trackbacks', 'custom-fields', 'revisions'),
    'rewrite' => true,
    'query_var' => true,
    'can_export' => true,
    'show_in_nav_menus' => true,
);

register_post_type('chart', $args);

Is there something I’m overlooking here? I don’t see why a draft post in this post type wouldn’t show up in the query above.

Related posts

Leave a Reply

3 comments

  1. Try passing it as an array.

    For example

    $args = array(
        'p' => 1234, 
        'post_type' => 'any',
        'post_status' => array('draft')
    );
    

    Or for all types

    $args = array(
        'p' => 1234, 
        'post_type' => 'any',
        'post_status' => array('publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit', 'trash')
    );
    
  2. I just came across this exact scenario. In my opinion it should work, but when I tried a combination of 'p' => 123 and 'post_status' => 'any', it would not return the post if the post status is draft.

    I was able to work around this by using 'post__in' => array( 123 ) instead. So:

    $args = array(
        'post__in' => array( 123 ),
        'post_type' => 'any',
        'post_status' => 'any',
    );
    $query = new WP_Query( $args );
    // ... etc.
    
  3. It looks like you might have an odd bug going on. Try replacing the oneline WP_Query with the following:

    $query = new WP_Query();
    $posts = $query->query( $args );