wordpress - 检查类别是否包含在 WooCommerce 中销售的任何产品?
问题描述
好吧,这听起来很容易,但我搜索了很多但找不到合适的答案。我想检查一个类别是否包含任何销售产品。
例如,有 10 个类别。我想获取包含销售产品的类别,并排除那些不包含任何销售项目的类别。
好吧,我是WP的新手。
解决方案
我对解决方案进行了很多搜索,最后我设法编写了自己的逻辑来回答这个问题。
脚步:
- 获取所有类别
- 获取销售产品的所有 id
- 遍历步骤 1 的类别
- 获取该类别的产品id
- 遍历步骤 4 的 id 的 id
- 检查该 id 是否存在于销售产品的 id 列表中
- 如果找到,将 flag 设置为 true 并退出
- 如果标志为假(没有产品在售),则取消设置类别
这是我的示例代码:
<?php
$args = array(
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => true,
'parent' => 0,
);
$categories = get_terms( 'product_cat', $args );
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$query_args = array(
'post_status' => 'publish',
'post_type' => 'product',
'posts_per_page' => -1,
'paged' => $paged,
'orderby' => 'ASC',
'meta_query' => WC()->query->get_meta_query(),
'post__in' => array_merge( array( 0 ), wc_get_product_ids_on_sale() )
);
$sale_products = new WP_Query( $query_args );
$products_ids_on_sale = wc_get_product_ids_on_sale();
if($sale_products->have_posts()) {
foreach ($categories as $key => $category) {
//get product ids
$category_product_ids = get_posts( array(
'post_type' => 'product',
'posts_per_page' => -1,
'post_status' => 'publish',
'fields' => 'ids',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $category->term_id,
'operator' => 'IN',
)
),
) );
$is_product_exist = false;
if ( ! empty($category_product_ids) ) {
foreach ($category_product_ids as $product_id) {
if (in_array($product_id, $products_ids_on_sale)) {
$is_product_exist = true;
break;
}
}
if ( $is_product_exist === false ) {
unset($categories[$key]);
}
}
}
wp_reset_query();
}
我在我的博客上写了一篇文章,并在https://www.kodementor.com/get-only-categories-that-contain-products -on-sale/ 上更详细地解释了产品和代码
推荐阅读
- r - 无法在闪亮中使用 Selectinput 进行选择
- django - 与 d3.js 一起使用时,Django 本地主机给我的 csv 文件一个错误
- azure - 没有 HttpTrigger 的 Azure 持久函数调用(自动启动)
- haskell - 在 Haskell 中不断收到输入“::”的解析错误?
- android - 如何更新每次搜索时显示我的搜索结果的浏览器
- c++ - 调用具有多个用于不同目的的数字的文本文件来创建商店和销售条形图
- javascript - 使用 Ajax 创建 PDF
- angular - 有人可以解释列表的这种行为吗?
- javascript - TypeScript:接口多态性问题
- angular - styleUrls 不适用于角度