Home › Forums › General Issues › Possible to Group By values of custom field › Reply To: Possible to Group By values of custom field
Hi @tjb1013
This is a good question, and one that can be accomplished with some simple PHP.
What you want to do is loop through your posts, load the custom field data, and then add them to the appropriate array. Then loop through this new array and display the data like so:
<?php
// vars
$posts = array( /* this is the array which holds all your posts. */);
$sorted = array();
// loop through posts
foreach( $posts as $p )
{
// load custom category:
$cat = get_field('trend_category');
// add to $sorted
if( !isset($sorted[ $cat ]) )
{
$sorted[ $cat ] = array();
}
$sorted[ $cat ][] = $p;
}
// now loop through sorted
foreach( $sorted as $cat_name => $cat_posts )
{
echo '<h3>' . $cat . '</h3>';
echo '<ul>';
foreach( $cat_posts as $p )
{
echo '<li>' . get_the_title( $p->ID ) . '</li>';
}
echo '</ul>';
}
?>
Please note the above code is untested and does not include any fail safe if statements. I hope it helps you understand how to solve your task.
Good luck!
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.