检查产品是否属于Woocommerce中的特定产品类别 [英] Check if a product belongs to a specific product category in Woocommerce

查看:46
本文介绍了检查产品是否属于Woocommerce中的特定产品类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Woocommerce中,我想检查一种产品是否属于产品类别"soap".

In Woocommerce, I would like to check if a product belongs to the product category "soap".

我正在使用以下代码:

<?php
    global $woocommerce;
    $items = $woocommerce->cart->get_cart();

        foreach($items as $item => $values) { 
            $_product =  wc_get_product( $values['data']->get_id() );
            $getProductDetail = wc_get_product( $values['product_id'] );
            echo "<b>".$_product->get_title() .'</b>  <br> Quantity: '.$values['quantity'].'<br>'; 
            // $category[] = $item->slug;
            // echo $category[0]->cat_name;
            $categories = $_product->get_categories();
            if(has_term( 'soap',$categories )){
                echo "success";
            }else{

                echo "nope";
            }
        }
?>

但是,当我遇到"nope"时,我无法使其正常工作.我认为这是问题所在的代码部分:

However I am not able to make it work as I get "nope". I think that this is the part of code where the problem is:

$categories = $_product->get_categories();
            if(has_term( 'soap',$categories )){
                echo "success";
            }else{

                echo "nope";
            }
        }

感谢您的帮助

推荐答案

更新:这是使其正常工作的正确方法:

Updated: Here is the correct way to make it work:

foreach(WC()->cart->get_cart() as $cart_item ) { 
    // The instance of the WC_Product object
    $_product = $cart_item['data'];
    // Some output
    echo '<b>'.$cart_item['data']->get_title().'</b>  <br>'; 
    echo 'Quantity: '.$cart_item['quantity'].'<br>'; 

    // Check for a specific product category
    if( has_term( 'soap', 'product_cat', $cart_item['product_id'] ) ){
        echo "success";
    } else {
        echo "nope";
    }
}

经过测试,可以正常工作.

Tested and work.

注释:

  • 要从购物车项目中获取 WC_Product 对象,只需使用 $ cart_item ['data']
  • 由于产品变体无法管理产品类别或产品标签,因此在这种情况下,我们获得了 $ cart_item ['product_id'] 允许的父变量产品ID.
    因此,请始终在购物车项目中使用 $ cart_item ['product_id'] 定位产品类别或产品标签.
  • Woocommerce产品类别是自定义分类法,与Wordpres类别不同.
  • product_cat 是与 has_term()和其他与术语相关的其他Wordpress功能一起使用的产品类别的分类法.
  • To get the WC_Product object from cart items, simply use $cart_item['data']
  • As product variations doesn't manage product categories or product tags, we get in this case the parent variable product ID that $cart_item['product_id'] allow…
    So always use $cart_item['product_id'] in cart items to target a product category or a product tag.
  • Woocommerce Product category is a custom taxonomy, different than Wordpres categories.
  • product_cat is the taxonomy for product categories to be used with has_term() and some other Wordpress functions related to terms.

这篇关于检查产品是否属于Woocommerce中的特定产品类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆