I don’t think WP_Query
returns the meta fields for you as well. So you need to loop over the posts and run get_post_meta()
manually. Assuming one office
has at max one _octopus_id
, you could write it like this:
// here we will store the ids
$octopiIds = [];
$query = new WP_Query([
'post_type' => 'office',
'post_status' => 'any',
'posts_per_page' => 10,
'meta_query' => [
[
'key' => '_octopus_id',
],
]
]);
while ($query->have_posts()) {
$query->the_post();
$octopiIds[] = get_post_meta(get_the_ID(), '_octopus_id', true);
}
wp_reset_postdata();
Do you really need the pagination of WP_Query
? If not, I would suggest writing your own query via $wpdb
s get_col()
, as it can save you alot of queries. The code above will create at least 11 queries (1 for WP_Query
, 1 for each post to get the meta), but you can do this in only one.
(untested)
global $wpdb;
$octopiIds = $wpdb->get_cols(
$wpdb->query("
SELECT DISTINCT pm.meta_value
FROM {$wpdb->posts} AS p
INNER JOIN {$wpdb->postmeta} AS pm
ON p.ID = pm.post_id AND pm.meta_key = '_octopus_id'
WHERE pm.meta_value != '' AND pm.meta_value IS NOT NULL
")
);
As an additional note, if you’re storing some kind of relationship between octopi and offices here, consider using a taxonomy instead of postmeta, as it will speed things up alot.