Support

Account

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 🙂