Question

Based on a category ID, I am trying to retrieve the relevant products under that category. However, all category ID I tried seems to return ALL products I have in the database and not those who belong to the category ID, here is my relevant code:

$args = array(
           'post_type' => 'product',
           'posts_per_page' => -1,
           'category' => 24
         );

$loop = new WP_Query( $args );


while ( $loop->have_posts() ) : $loop->the_post(); 

echo '<br /><a href="'.get_permalink().'">' . woocommerce_get_product_thumbnail().' '.the_title().'</a>';

endwhile; 
wp_reset_query(); 

Even if I ommit the category argument, the code still returning All products. How to fix that so I get only the relevant products for the specified category ID?

Thanks in advance

Was it helpful?

Solution

Based on Anand comments, I figured out the way to do so:

$term = get_term($_GET['catId'],'product_cat');// first parameter is the cat ID

$args = array( 'post_type' => 'product',
               'posts_per_page' => -1,// unlimited posts
               'product_cat' => $term->name,// Pass the category name
        );

More info here: http://codex.wordpress.org/Function_Reference/get_term

OTHER TIPS

$term = get_term( 24, 'product_cat' );

$args = array(
           'post_type' => 'product',
           'posts_per_page' => -1,
           'product_cat' => $term->name
         );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top