我怀疑主要的问题是你应该使用WP_Query
对象而不是get_posts()
. 默认情况下,后者仅返回post\\u类型为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 要了解更多关于类别定位工作原理的详细信息,通常通过slug而不是ID来检索它更有用!