这快把我逼疯了。我知道有人问过很多次,但我想不出来。我正在尝试显示WooCommerce产品的列表,这是一种自定义的“产品”post类型。我想按“product\\u cat”分类法对其进行排序。
在下面的代码中,内部while循环(query)-应该-只显示每个product_cat的产品,而是显示-all-产品。
为什么查询不过滤每个product\\u 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!\');
}
最合适的回答,由SO网友:TheDeadMedic 整理而成
你错过了tax_query
键,它需要是嵌套数组:
$args = array(
\'post_type\' => \'product\',
\'posts_per_page\' => -1,
\'tax_query\' => array(
array(
\'taxonomy\' => \'product_cat\',
\'terms\' => $cat_id,
\'field\' => \'term_id\',
),
),
);
检查
the documentation