Retrieve an array with all (published) post IDs for (queryable) post types having a custom field my_meta_field
with a value (string).
$args = array (
'post_type' => get_post_types(),
'showposts' => -1,
'meta_query' => array (
array (
'key' => 'my_meta_field',
'value' => '',
'compare' => '!='
)
),
'post_status' => 'publish',
'fields' => 'ids'
);
$query = new WP_Query($args);
Note, by calling new
constructor before WP_Query
we keep the query within the new instance and don’t pollute the global query.
So there is no need for wp_reset_query()
// use The Loop
while($query->have_posts()){
// do sth
echo get_the_ID().'<br>';
}
// or foreach yourself
foreach($query->posts as $post_id){
// do sth
echo $post_id.'<br>';
}
Here is the actual MySQL query, generated by our WP_Query instance.
SELECT wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND (
( wp_postmeta.meta_key = 'my_meta_field' AND CAST(wp_postmeta.meta_value AS CHAR) != '' )
) AND wp_posts.post_type IN ('post', 'page', 'attachment', 'revision', 'nav_menu_item') AND ((wp_posts.post_status = 'publish')) GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC
Alternatively you could query the database yourself using $wpdb. Here an example, omitting the JOIN to $wpdb->posts for filter status and type (too lazy!):
$wpdb->get_col( "SELECT post_id, meta_key, meta_value FROM $wpdb->postmeta where meta_key = 'my_meta_field'");