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"; }
You caused some confusion. On WooCommerce Cart Item:
$cart_item['data']
;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.woocommerce_package_rates
filter hook, use$package['contents']
instead ofWC()->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:
It should work for you.