首页 文章

检查购物车中是否使用了特定属性值(产品变体)

提问于
浏览
2

在WooCommerce中,我想检查购物车中的产品是否具有 'Varifocal' 属性(因此我可以显示/隐藏结帐字段) .

我正在努力获得所有具有属性'varifocal'的变体的id数组 . 如果有人能指出我正确的方向,我们将非常感激 .

分类法是 pa_lenses .

我目前有以下功能:

function varifocal() {
    // Add product IDs here
    $ids = array();

    // Products currently in the cart
    $cart_ids = array();

    // Find each product in the cart and add it to the $cart_ids array
    foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
        $cart_product = $values['data'];
        $cart_ids[]   = $cart_product->get_id();
    }

    // If one of the special products are in the cart, return true.
    if ( ! empty( array_intersect( $ids, $cart_ids ) ) ) {
        return true;
    } else {
        return false;
    }
}

1 回答

  • 1
    • 更新了代码 -

    这是一个自定义条件函数,当在一个购物车项目(产品变体)中找到特定属性参数时,它将返回 true

    function is_attr_in_cart( $attribute_value ){
    
        $found = false;
    
        if( WC()->cart->is_empty() ) return $found;
        else {
    
            foreach ( WC()->cart->get_cart() as $cart_item ){
                // Product ID
                $product_id = $cart_item['product_id'];
    
                // Variation ID + attributes
                if( 0 != $cart_item['variation_id'] ){
                    $variation_id = $cart_item['variation_id'];
                    foreach( $cart_item['variation'] as $attribute_val ){
                        // comparing attribute parameter value with current attribute value
                        if ($attribute_val == $attribute_value) {
                            $found = true;
                            break;
                        }
                    }
                }
                if($found) break;
            }
    
            return $found;
        }
    }
    

    代码位于活动子主题(活动主题或任何插件文件)的function.php文件中 .

    代码经过测试和运行 .


    用法(示例)

    if( is_attr_in_cart( 'Varifocal' ) ){
        echo '"Varifocal" attribute value has been found in cart items<br>';
    } else {
        echo '"Varifocal" <strong>NOT FOUND!!!</strong><br>';
    }
    

    建议:如果购物车为空,此条件函数将返回false

相关问题