Is it possible to have several custom fields with the same name?
For example, I have a custom field called “promotion” for a CPT called “event”. Sometimes there are more than one promotion applied to the same event, each for a certain type of participant. So I’d like to have one “promotion” custom field with a value “X, A” and another “promotion” custom field with a value “Y, B”.
I tried to create this then retrieve it with get_post_meta()
and display the result with print_r()
, but all I get is one of the values only (“X, A”).
Here’s the code:
$event_promotion = get_post_meta($post->ID, "Event Promotion", true); print_r($event_promotion);
Perhaps it’s just not possible to proceed this way?
Yes, it’s possible to have multiple fields with the same key.
When using
get_post_meta($post_id, $key, $single)
, make sure you set the$single
parameter tofalse
(or just leave it off since it defaults tofalse
).or
This will return an array containing every value of the key (what you’re expecting). If you set
$single
totrue
it will return the first value of the specified key as a string (what you’re currently getting).References:
http://codex.wordpress.org/Custom_Fields
http://codex.wordpress.org/Function_Reference/get_post_meta
this is how PHP handles names. try naming your fields promotion[] to let PHP know it’s an array of elements.