Search code examples
phpwoocommercecartcustom-taxonomytaxonomy-terms

Get variation attributes label name and value products from WooCommerce cart


I should get all the data of the products in the cart (product names and attributes of individual products). As a reference I have this code that allows to display only one attribute per product.

Could you help me to find the solution to see all attributes? In the store there are 10 attributes in total

$taxonomy = 'pa_selezione-pezzi';

// Get an instance of the WC_Product Object (necessary if you don't have it)
// from a dynamic $product_id (or defined $product_id)
$product = wc_get_product($product_id);
// Iterating through the product attributes
foreach($product->get_attributes() as $attribute){
    // Targeting the defined attribute
    if( $attribute->get_name() == $taxonomy ){
        // Iterating through term IDs for this attribute (set for this product)
        foreach($attribute->get_options() as $term_id){
            // Get the term slug
            $term_slug = get_term( $term_id, $taxonomy )->slug;

            // Output
            $confirmation = str_ireplace("{term_slug}", $term_slug, $confirmation);
        }
    }
}

Solution

  • If you are looking to retrieve the product attributes set in product variation cart items, you can use the following code example:

    // loop through product attributes
    foreach( WC()->cart->get_cart() as $item ) {
        if( ! empty($item['variation']) ) {
            // loop through product attributes
            foreach($item['variation'] as $attribute => $term_name )  {
                $taxonomy       = str_replace('attribute_', '', $attribute);
                $attribute_name = wc_attribute_label($taxonomy);
                $term_name      = get_term_by( 'slug, $term_name, $taxonomy)->name;
            }
        }
    }
    

    Tested and works