admin管理员组

文章数量:1302274

I'm currently using this to filter out only posts that have a specific custom image attachment field value. But it's returning 0. I used this method for other custom fields and it worked great. Is there something I need to do differently to get attachment images?

$args = array(
'post_type' => 'speakers',
'post_status' => array('publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit'), 
'post_per_page' => -1,
'meta_key' => 'speaker_promo_image',
'meta_query' => array(
    array(
        'key'     => 'speaker_promo_image',
        'value' => '',
        'compare' => '!=',
    )
  ) 
);
// The Query
$posts = new WP_Query( $args );
$the_count = $posts->post_count;

I'm currently using this to filter out only posts that have a specific custom image attachment field value. But it's returning 0. I used this method for other custom fields and it worked great. Is there something I need to do differently to get attachment images?

$args = array(
'post_type' => 'speakers',
'post_status' => array('publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit'), 
'post_per_page' => -1,
'meta_key' => 'speaker_promo_image',
'meta_query' => array(
    array(
        'key'     => 'speaker_promo_image',
        'value' => '',
        'compare' => '!=',
    )
  ) 
);
// The Query
$posts = new WP_Query( $args );
$the_count = $posts->post_count;
Share Improve this question asked Mar 8, 2021 at 19:51 Charles DavelCharles Davel 111 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

I ended up figuring it out. I installed the wordpress plugin "Query Wrangler" which helped me build exactly what I was trying to figure out. What was the missing key was instead of the value being '' on the post where the custom field didn't appear, I should have put '0'.

Here's the final working code:

$args = array (
 'paged' => 1,
 'posts_per_page' => '-1',
 'offset' => 0,
 'post_status' => array('publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit'),
 'ignore_sticky_posts' => 0,
 'orderby' => 'date',
 'order' => 'DESC',
 'post_type' => 'speakers',
 'meta_query' => array (
    0 => array (
      'key' => 'speaker_promo_image',
      'value' => '0',
      'compare' => '!=',
      'type' => 'CHAR',
    ),
  ),
  'meta_key' => 'speaker_promo_image',
);

本文标签: wp queryHow can I get the number of custom post type posts that have a specific attachment image set