1

I am able to get a list of its subcategories in a category archive page using below code in archive-product.php but I want to display the list of the products currently assigned to each subcategory.

<?php
    $parentid = get_queried_object_id();
    $args = array(
        'parent' => $parentid
    );
    $categories = get_terms(
        'product_cat', $args
    );
    if ( $categories ) {
        foreach ( $categories as $category ) {
            echo $category->name;
        }
    }
?>

Example:

Subcategory 1

  • Product 1 of Subcategory 1
  • Product 2 of Subcategory 1


Subcategory 2

  • Product 1 of Subcategory 2
  • Product 2 of Subcategory 2

I am still learning WordPress so any help will be highly appreciated.

1
<?php
    $parentid = get_queried_object_id();
    $args = array(
        'parent' => $parentid
    );
    $categories = get_terms(
        'product_cat', $args
    );
    if ( $categories ) :
        foreach ( $categories as $category ) :
            echo esc_html($category->name);
            $products = new WP_Query( array(
                'post_type' => 'product',
                'tax_query' => array(
                    array(
                        'taxonomy' => 'product_cat',
                        'field' => 'slug',
                        'terms' => $category->slug,
                    ),
                ) 
            ) );
            if ( $products->have_posts() ) :
            ?>
                <ul>
                    <?php while ( $products->have_posts() ) : $products->the_post(); ?>
                        <li><?php the_title(); ?></li>
                    <?php endwhile; ?>
                </ul>
            <?php
                wp_reset_postdata();
            endif;
        endforeach;
    endif;
?>

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.