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

Checking that a specific attribute value is used in a cart Item (product variation)

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

我正在努力获取具有属性 '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;
    }
}

这是一个自定义条件函数,当在一个购物车项目中找到特定属性参数时,它将 return 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 文件。已测试并有效。


USAGE (example)

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>';
}

Advice: This conditional function will return false if cart is empty