I was able to display the single value of my custom meta field with comma separated using this code:

$ct = get_post_meta($post->ID, 'ct', true);
echo $ct;

And here's an output:

USA, UK, China, Hong Kong

I needed the output to be:

<span>USA</span>, <span>UK</span>, <span>China</span>, <span>Hong Kong</span>

Is it possible? If so, a sample code would really help a lot or any reference you might know.

closed as off-topic by Tom J Nowell Aug 15 '17 at 12:58

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

  • Yes it's possible, but it's not a WordPress problem, it's a generic PHP one, look at the explode function. As a sidenote, you should use a taxonomy to store that information, not post meta – Tom J Nowell Aug 15 '17 at 12:58

If you are storing your meta values as a single string separated by commas, you can use the native PHP explode() to store them in an array:

$ct = get_post_meta($post->ID, 'ct', true);
// Store them in an array
$country_array = explode(',' , $ct);
// Run a loop and echo them
foreach( $country_array as $key => $country ){
    echo "<span>{$country}</span>";
    echo ( ( $key < ( count( $country_array ) -1 ) ) ? ', ':'' );

This might cause issue if you have a value like this:

Hong kong, China

Better yet save them as an array, instead of a single string.

Even better is to use custom taxonomy named country, and then use the_terms() to output them. This function allows you to add separator and before & after texts:

the_terms( $post->ID, 'country', '<span>', ',', '</span> );
  • Thanks! the php explode() worked. Im storing the meta values as single string. – Archangel17 Aug 15 '17 at 13:35
  • There's a problem tho. Why when using foreach to echo each value from array, it doubles the last value. For example, the input value to the meta field is: USA, UK, China, Hong Kong Then the outcame became: <span>USA</span>, <span>UK</span>, <span>China</span>, <span>Hong Kong</span>, Hong Kong The last value is being echoed twice. – Archangel17 Aug 15 '17 at 13:45
  • That should not happen. Please use print_r($country_array); and see if the result is duplicated in that too. – Jack Johansson Aug 15 '17 at 13:49
  • Tested it with print_r($country_array); and the result isn't duplicated. Just on the foreach loop. – Archangel17 Aug 15 '17 at 14:18
  • 1
    I've tested the code and it works fine for me, here is a screenshot. I've even added a conditional to remove the last comma. – Jack Johansson Aug 15 '17 at 14:30

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