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 );
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 );
Share
Improve this question
edited May 10, 2019 at 17:21
nmr
4,5672 gold badges17 silver badges25 bronze badges
asked May 1, 2019 at 23:41
Jobbie DaddyJobbie Daddy
771 silver badge8 bronze badges
2
|
2 Answers
Reset to default 3As @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
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'] = '';
$keys = get_post_meta( $post->ID );
and$keys
would contain all the available metadata for the post. E.g.$keys['image']
– Sally CJ Commented May 2, 2019 at 1:54