Home › Forums › Front-end Issues › Grouping Results by Field on the Front-end › Reply To: Grouping Results by Field on the Front-end
Hi @jeathree
There are two methods that I can think for your case.
First, you can loop trough the available categories and query the posts based on it like this:
$args = array(
'post_type' => 'nldf',
'posts_per_page' => -1,
'post_parent' => $post->ID,
'meta_key' => 'nldf_category_type',
'meta_value' => $the_category,
'order' => 'ASC',
'orderby' => 'menu_order'
);
Where $the_category
is the category in the loop.
The second method, you can get the posts by using the get_posts() function instead of the WP_Query class and then loop trough the posts and group it accordingly in an array. Maybe something like this (I assume that ‘nldf_category_type’ is a taxonomy field):
// Get all of the posts
$posts_array = get_posts( $args );
// Create a new array
$grouped_posts = array();
// Group it in a new array
foreach( $posts_array as $the_post ) {
$category = get_field('nldf_category_type', $the_post->ID);
// If the category group is not created yet, create it!
if( !isset($grouped_posts[$category->name]) ){
$grouped_posts[$category->name] = array();
}
// Put the post in the group
$grouped_posts[$category->name][] = $the_post;
}
// Loop it!
foreach( $grouped_posts as $cat_name => $the_posts ) {
echo $cat_name;
foreach( $the_posts as $the_post ){
echo $the_post->title;
}
}
I hope this helps 🙂
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!
Are you building WordPress sites with ACF and @BeaverBuilder, and wanted to use your ACF Blocks in both the block editor and Beaver Builder?
— Advanced Custom Fields (@wp_acf) May 10, 2023
The BB team recently added support for using ACF Blocks in Beaver Builder. Check it out 👇https://t.co/UalEIa5aQi
© 2023 Advanced Custom Fields.
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 Cookie Policy. If you continue to use this site, you consent to our use of cookies.