Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Loop through advanced custom fields repeater, grouped by select WordPress

  • SOLVED

I need to loop through an advanced custom fields repeater, grouping and ordering the results by a select field. It's a staff list, so I have a repeater with a name, title, picture and bio as well as staff group select field with a number of different groups that a person can be assigned to.

For more details visit http://support.advancedcustomfields.com/discussion/comment/19699, where the question of how to do this is answered by the plugin developer (see the June 15 comment), but remains beyond my ability to implement.

<strong>Group 1 (team_group)</strong>

Name 1 (team_name)
Title 1 (team_title)
Image 1 (team_image)
Bio 1 (team_bio)

Name 2
Title 2
Image 2
Bio 2

<strong>Group 2</strong>

Name 3
Title 3
Image 3
Bio 3

Answers (1)

2013-06-21

Ross Wilson answers:

So you should be able to do something like this (comments inline with code):

$grouped_members = array();
$members= get_field('staff_members'); //this should be whatever the name of your repeater field is
if($members)
{
// Create the array structure with array[group][member]
foreach($members as $member)
{
$grouped_members[$member['team_group']][] = $member;
}

//loop through each group created
foreach($grouped_members as $members){
//print out the name of the group - grabbing it from the first member
echo '<h1>'.$members[0]['team_group'].'</h1>';

//then loop through each member in the group
foreach($members as $member){
//output the member details
echo $member['team_name'] . '</br>';
echo $member['team_title'] . '</br>';
echo $member['team_bio'] . '</br>';
}
}

}


Christopher comments:

Wouldn't you know, that worked perfectly (with the one missing semi-colon). Many thanks Ross!