Search code examples
phpwordpresswoocommercecartproduct-variations

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


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

Solution

  • 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