0

Using the Advanced Custom Fields plugin and I've got a shortcode going for a repeater field, but it returns the list at the content top. I changed it from an echo to a return, which I understood would fix the issue of it appearing at the top of the content, but it didn't and now it strips all the html out and returns the whole thing as one big text block. Clearly I'm doing something wrong.

function teamlist_shortcode($atts, $content = null) {
if (get_field('aw_team_members')):
while (has_sub_field('aw_team_members')):

$string = '<h3>' . the_sub_field('team_name') . '</h3><h3 class="subtitle">' . the_sub_field('team_title') . '</h3>' . the_sub_field('team_bio');

endwhile;
return $string;
endif; 
}
add_shortcode('teamlist', 'teamlist_shortcode');
1

the_sub_field echos content. The docs are quite clear about that.

The the_sub_field function is used with the repeater field and the flexible content field (license key required) to display a sub field value. When looping through one of these fields, this function displays a sub field from the current row.

This is the same as echo get_sub_field();

http://www.advancedcustomfields.com/resources/functions/the_sub_field/

Use get_sub_field to construct a string.

The function names follow a common (but not universal) WordPress pattern or use the the_ prefix for functions that echo and the get_ prefix for functions that return.

However, there will still be a problem in that your code completely overwrites $string at each iteration. You need to concatenate a string with all of the results, which you can do easily with .= instead of just =.

function teamlist_shortcode($atts, $content = null) {
  if (get_field('aw_team_members')):
    $string = '';
    while (has_sub_field('aw_team_members')):
      $string .= '<h3>' . the_sub_field('team_name') . '</h3><h3 class="subtitle">' . the_sub_field('team_title') . '</h3>' . the_sub_field('team_bio');
    endwhile;
    return $string;
  endif; 
}
add_shortcode('teamlist', 'teamlist_shortcode');
3
  • Thanks very much, I had forgotten about that. Unfortunately, now it only returns the last entry in the repeater field, so I still have something wrong. – Christopher Jun 19 '13 at 14:57
  • @Christopher : You are overwriting the string at each iteration of the loop. See the edit. – s_ha_dum Jun 19 '13 at 15:02
  • Thank you dearly. Still so much to learn. That was an enormous help. – Christopher Jun 19 '13 at 15:06

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.