Search code examples
phpwoocommercecarttaxonomy-termsproduct-variations

How to get product variation attribute slugs from Woocommerce cart items


I need to check the cart to see if a specific product attribute has been added on any product. (This is within a customized shipping function hooked to woocommerce_package_rates. )

I have the variation ID of each item in the cart, but I can not figure out how to get that item's variation slug...

foreach (WC()->cart->get_cart() as $cart_item) {

    // $product_in_cart = $cart_item['product_id'];
    
    $variation_id = $cart_item['variation_id'] > 0 ? $cart_item['variation_id'] : 
    $cart_item['product_id'];
    
    $variation = wc_get_product($variation_id);

    $variation_name = $variation->get_formatted_name(); //I want to get the slug instead.

    // if there is the swatch variation of any product in the cart.
    if (  $variation_name == 'swatch') $cart_has_swatch = "true"; 
    
}

Solution

  • You are making some confusions. On WooCommerce cart items:

    • the product variation object is always $cart_item['data'];
    • the variation attributes are accessible via $cart_item['variation'] (which is an array of product attribute taxonomy, product attribute slug value pairs).
    • $variation->get_formatted_name() is the product variation name (formatted), so not a variation product attribute.
    • With woocommerce_package_rates filter hook, use $package['contents'] instead of WC()->cart->get_cart().

    Your question is not very clear, as we don't know if you are searching the term "swatch" in the attribute taxonomy or in the attribute slug value.

    Try the following:

    add_filter( 'woocommerce_package_rates', 'filtering_woocommerce_package_rates', 10, 2 );
    function filtering_woocommerce_package_rates( $rates, $package ) {
        $cart_has_swatch = false; // initializing
    
        // Loop through cart items in this shipping package
        foreach( $package['contents'] as $cart_item ) {
            // Check for product variation attributes
            if( ! empty($cart_item['variation']) ) {
                // Loop through product attributes for this variation
                foreach( $cart_item['variation'] as $attr_tax => $attr_slug ) {
                    // Check if the world 'swatch' is found
                    if ( strpos($attr_tax, 'swatch') !== false || strpos( strtolower($attr_slug), 'swatch') !== false ) {
                        $cart_has_swatch = true; // 'swatch' found
                        break; // Stop the loop
                    }
                }
            }
        }
    
        if ( $cart_has_swatch ) {
            // Do something
        }
    
    
        return $rates;
    }
    

    It should work for you.