On a page like taxonomy-product_cat.php - this function lists just the products for the called sub-category - bags:

$args = array( 'post_type' => 'product', 'product_cat' => 'bags')
$loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post();

I can hardcode list all the sub-categories and then dynamically list the products. I want to dynamically create the subcategory list with the associated products listed with it - what is the best way to do this? I am thinking that if I make the 'product_cat' => dynamic - is a way to achieve this?

  • do you mean the actual category of the category archive page, or a sub-category of that actual category? in what file are you using that code? – Michael Jan 23 '20 at 20:15

You shouldn't be using WP_Query at all. The standard loop will automatically display the correct posts.

while ( have_posts() ) : the_post();

  • This lists all products of the current parent category. There is no ordering into sub-category. Maybe my question is not clear enough and I will rewrite it. I am running a foreach loop that can list the subcategories, and I was looking for code to list that sub-categories products. When I put your code it it lists all parent category items under each subcategory so does not really work for me. But it did help me advance in a few other issues - thanks! – Jon Jan 26 '20 at 12:09

You can use get_queried_object(), within that object you can get the slug or id.

  • If the correct category is the "queried object" (past tense), why would they query it again? – Jacob Peattie Jan 24 '20 at 6:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.