Search code examples
wordpressadvanced-custom-fieldstaxonomy

Group WordPress posts by category


after several unsuccessful searches, I ask my question here. Indeed, I'm trying to display a list of posts grouped by categories:

CAT A

  • post1
  • post2
  • post3

CAT B

  • post4
  • post5
  • post6
  • post7 ...

Here is the code I tried. I can display the categories, but not the posts

<?php 
        $terms = get_terms( 'secteur', array(
            'orderby'    => 'count',
            'hide_empty' => 0
        ) );
        
        foreach( $terms as $term ) {
            $args = array(
                'post_type' => 'client',
                'posts_per_page' => '-1',
              'secteur' => $term->slug
            );
            $query = new WP_Query( $args );
  
            echo'<h3>' . $term->name . '</h3>';
           

                // Start the Loop
                while ( $query->have_posts() ) : $query->the_post(); 
                $secteur_dactivite = get_field( 'secteur_dactivite' );

                echo '<div class="cat-'.esc_html( $secteur_dactivite->slug ). '"><img src="'.get_field( 'logo' ).'"></div>';

                 endwhile;

            wp_reset_postdata();
 
        } 
    
    ?>

Solution

  • You need to use tax_query as an WP query attribute, instead of secteur.

    Try replacing that with:

    $args = array(
      'post_type' => 'client',
      'posts_per_page' => '-1',
      'tax_query' => array(
            array(
                'taxonomy' => 'secteur',
                'field'    => 'slug',
                'terms'    => $term -> slug,
            ),
        ),
    );