首页 > 解决方案 > 过滤自定义产品循环以从 WooCommerce 中的类别中获取产品

问题描述

我有这个功能,它在 WooCommerce 中调用我所有产品类型“promotion_package”:

<?php foreach ( (array) $products as $product ):

    if ( ! $product->is_type( 'promotion_package' ) || ! $product->is_purchasable() || $product->get_duration() <= 0 ) {
        continue;
    }

endforeach; ?>

我只想从“vip”产品类别中获得产品。

我尝试使用$product->get_categories()查找“vip”类别,但没有成功。

如何仅显示“vip”类别的产品?

标签: phpwordpresswoocommerceproducttaxonomy-terms

解决方案


您可以尝试has_term()以下 procuct 类别分类的条件函数'product_cat'

<?php 
    $categories = array('vip'); // Your categories (can be terms Ids, slugs or names)

    foreach ( (array) $products as $product ):

    if ( ! $product->is_type( 'promotion_package' ) || ! $product->is_purchasable() || $product->get_duration() <= 0 
    || ! has_term( $categories, 'product_cat', $product->get_id() ) ) {
        continue;
    }

    endforeach; 
?>

它应该工作,


推荐阅读