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:

    // 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!