首页 > 解决方案 > 检查类别是否包含在 WooCommerce 中销售的任何产品?

问题描述

好吧,这听起来很容易,但我搜索了很多但找不到合适的答案。我想检查一个类别是否包含任何销售产品。

例如,有 10 个类别。我想获取包含销售产品的类别,并排除那些不包含任何销售项目的类别。

好吧,我是WP的新手。

标签: wordpresswoocommerce

解决方案


我对解决方案进行了很多搜索,最后我设法编写了自己的逻辑来回答这个问题。

脚步:

  1. 获取所有类别
  2. 获取销售产品的所有 id
  3. 遍历步骤 1 的类别
  4. 获取该类别的产品id
  5. 遍历步骤 4 的 id 的 id
  6. 检查该 id 是否存在于销售产品的 id 列表中
  7. 如果找到,将 flag 设置为 true 并退出
  8. 如果标志为假(没有产品在售),则取消设置类别

这是我的示例代码:

<?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-c​​ontain-products -on-sale/ 上更详细地解释了产品和代码


推荐阅读