Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
    
How are you creating your CPT? Can you show code (if using code)? –  vancoder Apr 1 '13 at 19:35
    
@vancoder: hmm why are you asking, does it not occur the same thing with a normal WP post? –  drake035 Apr 1 '13 at 21:27
    
simply to ascertain how you are setting up your custom fields. If you are just using 'off the shelf' custom fields, then it doesn't matter. –  vancoder Apr 1 '13 at 21:34
    
You can have multiple custom field values using the same key. Using get_post_meta( get_the_ID(), 'your-key' ) should return an array containing every value using that key. Can you post the actual get_post_meta() code you're using? –  BigBagel Apr 1 '13 at 21:51
    
Here's the code : $event_promotion = get_post_meta($post->ID, "Event Promotion", true); print_r($event_promotion); –  drake035 Apr 2 '13 at 17:27
show 1 more comment

2 Answers

up vote 4 down vote accepted

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

share|improve this answer
add comment

this is how PHP handles names. try naming your fields promotion[] to let PHP know it's an array of elements.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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