1

This is driving me nuts. I know it's been asked a number of times but I can't figure it out. I'm trying to display a list of WooCommerce products--which are a custom post type of 'product'. I want to sort it by a taxonomy of 'product_cat'.

In the following code, the inner while loop (query) -should- display only the products for each product_cat, but instead, it displays -all- products.

Why isn't the query filtering each product_cat?

// loop through the categories
foreach ($cats as $cat) {
  $cat_id = $cat->term_id;
        $cat_slug = $cat->slug;
  // Make a header for the category
  echo "<h2>".$cat->slug.' '. $cat_id . "</h2>";
  // create a custom wordpress query

      $args = array(
          'post_type' => 'product',
            'posts_per_page' => -1,
            array(
                'taxonomy' => 'product_cat',
                'terms'    => $cat_id,
                'field'    => 'term_id',                    
            ),
        );
    $query = new WP_Query( $args );

        if ( $query->have_posts() ) {
            echo '<ul>';
            while ( $query->have_posts() ) {
                $query->the_post();
            $p = get_the_ID();
                echo '<li>' . get_the_title() . '</li>';
            }
            echo '</ul>';
            /* Restore original Post Data */
            wp_reset_postdata();
        } else {
            // no posts found
                echo('no posts!');  
    }
3

You're missing the tax_query key, and it needs to be a nested array:

$args = array(
    'post_type' => 'product',
    'posts_per_page' => -1,
    'tax_query' => array(
        array(
            'taxonomy' => 'product_cat',
            'terms' => $cat_id,
            'field' => 'term_id',
        ),
    ),
);

Check the documentation

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.