我怀疑主要问题是您应该使用WP_Query
对象而不是get_posts()
。默认情况下,后者只会返回post_type post
不是产品的商品,
因此,给定ID为26的类别,以下代码将返回其产品(WooCommerce 3+):
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'posts_per_page' => '12',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id', //This is optional, as it defaults to 'term_id'
'terms' => 26,
'operator' => 'IN' // Possible values are 'IN', 'NOT IN', 'AND'.
),
array(
'taxonomy' => 'product_visibility',
'field' => 'slug',
'terms' => 'exclude-from-catalog', // Possibly 'exclude-from-search' too
'operator' => 'NOT IN'
)
)
);
$products = new WP_Query($args);
var_dump($products);
在WooCommerce的早期版本中,可见性存储为元字段,因此代码为:
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'posts_per_page' => '12',
'meta_query' => array(
array(
'key' => '_visibility',
'value' => array('catalog', 'visible'),
'compare' => 'IN'
)
),
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id', //This is optional, as it defaults to 'term_id'
'terms' => 26,
'operator' => 'IN' // Possible values are 'IN', 'NOT IN', 'AND'.
)
)
);
$products = new WP_Query($args);
var_dump($products);
在这里,我们只返回可见的产品,每页12个。
浏览http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters,以获取有关类别定位工作原理的更多详细信息-按段检索比按ID检索通常更有用!
category
还是product_category
?