Answer the question
In order to leave comments, you need to log in
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:
Answer the question
In order to leave comments, you need to log in
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; ?>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question