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

若如初见. 提交于 2019-12-12 13:12:38

问题


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).

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.

The taxonomy is pa_lenses.

I currently have the following function:

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:


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

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


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



来源:https://stackoverflow.com/questions/41304266/checking-that-a-specific-attribute-value-is-used-in-a-cart-item-product-variati

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!