检查购物车中是否使用了特定的属性值(产品变体) [英] Checking that a specific attribute value is used in a cart Item (product variation)

查看:77
本文介绍了检查购物车中是否使用了特定的属性值(产品变体)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In WooCommerce, I would like to check if the products in the shopping cart have the attribute 'Varifocal' (so I can show/hide checkout fields).

我正在努力获取所有具有'varifocal'属性的变体的ID数组.如果有人能指出我正确的方向,将不胜感激.

I'm struggling to get an array of id's of all the variations which have the attribute 'varifocal'. It would be really appreciated if someone can point me in the right direction.

分类法为 pa_lenses .

The taxonomy is 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;
    }
}

推荐答案

这是一个自定义条件函数,当在一个购物车项目 true >(产品变体形式):

Here is a custom conditional function that will return true when the a specific attribute argument is found in one cart item (product variation):

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文件中..经过测试,可以正常工作.

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

用法 (示例)

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

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

这篇关于检查购物车中是否使用了特定的属性值(产品变体)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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