我的代码总是返回指定类别ID的所有产品

时间:2014-05-07 10:46:23

标签: wordpress woocommerce

根据类别ID,我正在尝试检索该类别下的相关产品。但是,我尝试的所有类别ID似乎都返回了我在数据库中的所有产品,而不是那些属于类别ID的产品,这是我的相关代码:

$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(); 

即使我省略了类别参数,代码仍会返回所有产品。如何解决这个问题,以便我只获得指定类别ID的相关产品?

提前致谢

2 个答案:

答案 0 :(得分:1)

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

$args = array(
           'post_type' => 'product',
           'posts_per_page' => -1,
           'product_cat' => $term->name
         );

答案 1 :(得分:1)

基于Anand评论,我想出了这样做的方法:

$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
        );

此处有更多信息:http://codex.wordpress.org/Function_Reference/get_term