【问题标题】:Checking that a specific attribute value is used in a cart Item (product variation)检查购物车项目(产品变体)中是否使用了特定属性值
【发布时间】:2017-05-09 07:49:24
【问题描述】:

在 WooCommerce 中,我想检查购物车中的产品是否具有属性 '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;
    }
}

【问题讨论】:

    标签: php wordpress woocommerce cart variations


    【解决方案1】:

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

    function is_attr_in_cart( $attribute_slug_term ){
        $found = false; // Initializing
    
        if( WC()->cart->is_empty() ) 
            return $found; // Exit
        else {
            // Loop through cart items
            foreach ( WC()->cart->get_cart() as $cart_item ){
                if( $cart_item['variation_id'] > 0 ){
                    // Loop through product attributes values set for the variation
                    foreach( $cart_item['variation'] as $term_slug ){
                        // comparing attribute term value with current attribute value
                        if ( $term_slug === $attribute_slug_term ) {
                            $found = true;
                            break; // Stop current loop
                        }
                    }
                }
                if ($found) break; // Stop the first loop
            }
            return $found;
        }
    }
    

    代码在您的活动子主题(或活动主题)的functions.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

    【讨论】:

    • 更好的解决方案。我测试了它并且它有效。非常感谢!
    猜你喜欢
    • 2019-05-25
    • 2018-10-13
    • 1970-01-01
    • 2019-06-15
    • 2011-04-09
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    相关资源
    最近更新 更多