Home  >  Q&A  >  body text

How to get product variant attribute slugs from Woocommerce cart item

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

I have the variant ID for each item in my cart, but I don't know how to get the variant slug for that item...

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

P粉895187266P粉895187266232 days ago370

reply all(1)I'll reply

  • P粉600402085

    P粉6004020852024-02-05 09:13:39

    You caused some confusion. On WooCommerce Cart Item:

    • The product variation object is always $cart_item['data'];
    • The variation attribute can be accessed via $cart_item['variation'] (this is an array of product attribute taxonomy, product attribute slug value pairs) .
    • $variation->get_formatted_name() is the product variation name (formatted) and therefore is not a variation product attribute. <​​/li>
    • Use the woocommerce_package_rates filter hook, use $package['contents'] instead of WC()->cart->get_cart() .

    Your question is not very clear because we don't know if you are searching for the term "sample" in the attribute taxonomy or the attribute segment 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.

    reply
    0
  • Cancelreply