Leave a Reply

2 comments

  1. First, just pass your arguments to the constructor of WP_Query as this is both cleaner, and the way you’re supposed to do it according to the Codex documentation of the class.

    You should be constructing things like this:

    $my_key_query_args = array(
       'post_type'   => 'attachment',
       'post_status' => 'inherit',
       'meta_query'  => array(
           array(
               'key'     => 'my_key',
               'value'   => '1',
               'compare' => '=',
               'type'    => 'BINARY'
    
          )
       )
    );
    
    $my_key_query = new WP_Query( $my_key_query_args );
    

    Second, notice the added post_status parameter of my array. By default attachments are added with a post status of “inherit,” but WP_Query will look for posts with the status of “published,” “draft,” or “pending.” (See the documentation of that parameter as well).

    So there’s no bug here, we just forgot to check the defaults for all parameters passed into the object.

    There’s a note on the “attachment” option for the post_type parameter that calls out this requirement:

    The default WP_Query sets 'post_status'=>'published', but attachments default to 'post_status'=>'inherit' so you’ll need to set the status to 'inherit' or 'any'.

  2. I believe your problem is that you’re trying to use WP_Query like get_posts(). It seems quite possible that the query is working, but you just can’t see the results. WP_Query returns a query object that you loop through like this:

    ...
    $my_query = WP_Query( $args );
    while( $my_query->have_posts() ) : $my_query->the_post();
    
    // do your thing
    
    endwhile;
    

    Also, note that I used $my_query. I’m a little fuzzy on this, but I believe $query may be a reserved variable from WordPress, and either way, it’s often better if you make that query a little-more human-readable (maybe event $attachment_meta_query or something).