1

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; ?> 
1

use php's implode to join array elements with a string:

<?php
if( $bands = get_post_meta($post->ID, 'band') ):
    ?>
    <strong>Band:</strong> <?php echo implode( $bands, ', ' ); ?><br />
    <?php
endif;
?>

EDIT- another version of above, pluralizing the label depending on single or multiple meta values:

<?php
if( $bands = get_post_meta($post->ID, 'band') ):
    $label = count( $bands ) > 1 ? 'Bands' : 'Band';
    ?>
    <strong><?php echo $label; ?>:</strong> <?php echo implode( $bands, ', ' ); ?><br />
    <?php
endif;
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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