Multiple custom fields with the same name

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?

2 Answers
2

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 to false (or just leave it off since it defaults to false).

get_post_meta( $post->ID, 'Event Promotion', false )

or

get_post_meta( $post->ID, 'Event Promotion' )

This will return an array containing every value of the key (what you’re expecting). If you set $single to true 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

Leave a Comment