2

I am building a custom solution where I am needing to obtain all the meta values for a post into an array. I have many "keys". Is there a way to loop through them all without doing this? I have the post ID at this point in my script.

$image_meta =  get_post_meta( $post->ID, 'image', true );

// car year

$car_year = get_post_meta( $post->ID, 'car_year', true );

// car mileage

$car_mileage = get_post_meta( $post->ID, 'car_mileage', true );

// car price

$car_price = get_post_meta( $post->ID, 'car_price', true );

// car model

$car_model = get_post_meta( $post->ID, 'car_model', true );
  • 1
    Not sure if I understand it, but you could do $keys = get_post_meta( $post->ID ); and $keys would contain all the available metadata for the post. E.g. $keys['image'] – Sally CJ May 2 at 1:54
  • 2
    Well, maybe you could post more code? And by "the types", you mean post types? What do you mean by "without defining them or knowing their count"? – Sally CJ May 2 at 2:39
3

As @Sally CJ noted in the comment to your question, you should just omit the meta key:

$meta = get_post_meta( $post->ID, '', true );

echo $meta['car_year']; // 2005

In PHP 7.1 you can use array destructing:

[
    'image_meta'  => $image_meta,
    'car_year'    => $car_year,
    'car_mileage' => $car_mileage,
    'car_price'   => $car_price,
    'car_model'   => $car_model,
] = get_post_meta( $post->ID, '', true );

echo $car_year; // 2005
1

I've had similiar needs in the past and as I didn't know about array destructing @phatskat mentioned I created a helper function to do the looping for me.

Helper function,

function get_keyed_meta_data_array( int $post_id, array $keys ) {
  $keyed_meta = array();
  $post_meta = get_post_meta( $post_id, '', true );

  foreach ( $keys as $key ) {
    if ( isset( $post_meta[$key] ) ) {
      $keyed_meta[$key] = $post_meta[$key];
    } else {
      $keyed_meta[$key] = '';
    }
  }

  return $keyed_meta;
}

Usage,

$keys = array(
  'image',
  'car_year',
  'car_mileage',
  'car_price',
  'car_model'
); // key array could also be returned from a config function for DRY purposes

$data = get_keyed_meta_data_array( $post->ID, $keys );
// $data['car_year'] = 2019;
// $data['car_mileage'] = 123;    
// $data['car_model'] = '';

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.