0

How could one grab the post meta key of _octopus_id and store that as an array.

Here is what I'm trying to achieve:

  • Call the WP_Query and pull all the offices with _octopus_id
  • Use the value of _octopus_id and store it in an array
  • End goal: Just print out a array with just the _octopus_id values

Could someone tell me what I might be doing wrong? The is_array($posts) prints out true, but I just can't figure out how to store the keys value there.

Full code:

    /* Set the WP offices in an array */
    $ids = new WP_Query([
        'post_type' => 'office',
        'post_status' => 'any',
        'posts_per_page' => 10,
        'meta_query'     => array(
            array(
                'key'        => '_octopus_id',
            ),
        )
    ]);

    $posts[] = $ids->posts;

    var_dump($posts);
    var_dump(is_array($posts));
2
  • So you want an array of _octopus_id that are currently used by at least one office? – kero Nov 11 '19 at 17:40
  • @kero, Correct - I'd like to loop through those 10 posts and store the _octopus_id key values into an array. – DevSem Nov 11 '19 at 17:40
1

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 $wpdbs 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.

1
  • 1
    This helped so much! Thanks a bunch! – DevSem Nov 11 '19 at 19:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.