i have some fields, which i would like to print out with an shortcode with one attribute. i have normal variables and arrays, with my code only the first value of an array is printed... should i use implode?

function leweb_test( $atts ) {
  $atts = shortcode_atts( array(
            'field' => 'user_email',  
  ) , $atts );

  $value = um_user( $atts['field'] );

  if( is_array( $value ) == TRUE ) {

    foreach( $value AS $field ) {
      return $field;
  } else { 
      return $value;

add_shortcode( 'leweb_test_shortcode', 'leweb_test' );
  • 1
    How do you want the result to look? A list? Comma separated? Oct 9, 2019 at 1:00

1 Answer 1


Shortcode should return string ready to append to content. You can’t return an array, because it won’t be printed correctly.

So if your shortcode should return an array, you have to figure out how this data should be formatted.

One way to do it is to use commas to separate the values:

return implode( ', ', $value );

Another way is to format it as an list (ul/ol):

$result = '<ul>';
foreach ( $values as $item ) {
    $result .= '<li>' . esc_html( $item ) . '</li>';
$result .= '</ul>';
 return $result;

And the biggest problem with your code is that you use return inside of foreach loop. If the function returns anything, then it stops working and exits. So if you do this:

foreach( $value AS $field ) {
  return $field;

Then you literally say that you should loop through the array and in the first iteration the value should be returned (so the function should stop working after it). So yes - this loop will return only first item of an array.

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.