【问题标题】:WooCommerce: Show only terms with products in stockWooCommerce:仅显示有库存产品的条款
【发布时间】:2022-11-17 22:18:56
【问题描述】:
我正在使用 get_terms 来显示术语列表。到目前为止它工作正常。
但我想隐藏所有缺货产品的术语。
如果我使用'hide_empty' => true,它将无法工作,因为产品已经发布。
有没有办法将 _stock 元字段添加到 get_terms 函数?
不幸的是我必须使用get_terms。
这是我的代码(它要大得多,但仅此而已):
$terms = get_terms( array(
'taxonomy' => 'product_tax',
'orderby' => 'name',
'hide_empty' => true,
) );
【问题讨论】:
标签:
php
wordpress
woocommerce
taxonomy-terms
【解决方案1】:
5 个月前,但也许它会对某人有所帮助:我面临同样的问题,我发现的只是制作一个 foreach 来取消设置空值。
foreach ($terms as $key => $term) {
$args = array(
'post_type' => 'product',
'paged' => 1,
'posts_per_page' => 1,
'order' => 'DESC',
'post_status' => 'publish',
'orderby' => 'publish_date',
'meta_query' => array( array(
'key' => '_stock_status',
'value' => 'instock',
) ),
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $term->term_id
)
)
);
$loop = new WP_Query( $args );
if($loop->post_count < 1) {
unset($terms[$key]);
}
}