O
O
ole922018-07-24 13:53:00
WordPress
ole92, 2018-07-24 13:53:00

How to display categories and subcategories and all articles?

Hello. I've run into this issue many times and haven't found a solution. I will be glad to any advice.
Task:
There are categories and subcategories in them products. Products must have a separate page. I plan to organize posts. But I can’t figure out how to display all categories, subcategories and products in them. So the structure is like this.
Main category >
Subcategory >
- Goods;
- Product;
- Product:
Main category 2>
Subcategory >
- Product;
- Product;
- Product:
Main category 3>
Subcategory >
- Product;
- Product;
- Product:
Here is the layout itself:
5b5705024fe25250456501.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan Hasanli, 2018-07-24
@ole92

Hello!
You need to use a loop within a loop...
For example, with foreach you get categories and subcategories, and then with while you get articles.
A simple example that outputs Categories and entries for them

<?php 	$post_type = 'product';
    $product_args = array(
        'taxonomy' => 'product_cat',
        'hide_empty' => true,
        );
        $terms = get_terms( $product_args );
          foreach( $terms as $term ) : ?>
              <div class="title"><span><?php echo $term->name; ?></span></div>
              <?php $args = array(
                      'post_type' => $post_type,
                      'posts_per_page' => -1,  //show all posts
                      'tax_query' => array(
                          array(
                              'taxonomy' => 'product_cat',
                              'field' => 'slug',
                              'terms' => $term->slug,
                          )
                      )
                  );?>
              <?php $posts = new WP_Query($args);
              if( $posts->have_posts() ): while( $posts->have_posts() ) : $posts->the_post(); ?>
       			<div class="catalog-all-product">
                    	<div class="images">
                          <?php the_post_thumbnail(); ?>
                    	</div>
                        <div class="name">
                        	<a href="<?php echo get_permalink(); ?>"><?php echo get_the_title(); ?></a>
                        </div>
                    </div>
              <?php endwhile; endif; ?>
<?php endforeach; ?>

Source - https://gist.github.com/DevinWalker/6fb2783c05b46a...
https://stackoverflow.com/questions/1780386/loopin...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question