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

标签 php wordpress woocommerce cart product-variations

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

最佳答案

这是一个自定义条件函数,当在一个购物车项目中找到特定属性参数时,它将返回 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

关于php - 检查购物车项目(产品变体)中是否使用了特定的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41304266/

相关文章:

php - 显示数据库内容? PHP/MySQL

php - 将空值设置为不在 MySQL 中的日期

php - 如何在 woocommerce 循环外使用变体和添加到购物车按钮

php - PHP4 中的 XPath 和值内容

css - 如何使用 CSS 去除 Wordpress 网站页脚下方的空白区域

javascript - 从 Javascript 中的对象数组重新创建对象

php - WordPress 网站 Hook 错误

php - Woocommerce 使用复选框追加销售

wordpress - WooCommerce在处理订单电子邮件中添加产品链接

php - 将 Codeigniter 从 1.7.2 升级到 3.1.6