I am having a heck of a time getting wordpress to display all values of a certain meta key correctly. I wonder if I am going about this the wrong way?
My end goal is to run a check to see if there is more than one custom field value in a key. If there is, each value should be listed with a comma delimiter, but no comma on the last value. If there is not, no comma should be used. I have tried two methods unsuccessfully. The first is get_post_meta:
<?php if(get_post_meta($post->ID, 'band', true)): ?>
<strong>Band:</strong> <?php echo get_post_meta($post->ID, 'band'); ?><br />
<?php endif; ?>
According to the codex, this should display all values of that key, but instead all it does is echo “array”. If I change $Single to true, like so:
<?php if(get_post_meta($post->ID, 'band', true)): ?>
<strong>Band:</strong> <?php echo get_post_meta($post->ID, 'band', true); ?><br />
<?php endif; ?>
it only returns the first value (but at least returns the value and not the word “array”.
The second method I have tried that sorta worked was get_post_custom_values. This does the trick, but I can’t work out how to a) run a check for multiple values or b) keep it from adding a comma to the last value.
<?php if(get_post_meta($post->ID, 'gear', true)): ?>
<strong>Gear: </strong>
<?php
$mykey_values = get_post_custom_values('gear');
foreach ( $mykey_values as $key => $value ) {
echo "$value, ";
}
?>
<?php endif; ?>
use php’s
implode
to join array elements with a string:EDIT- another version of above, pluralizing the label depending on single or multiple meta values: