SemFim Creative
SemFim Creative

Reputation: 55

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

Upvotes: 2

Views: 2054

Answers (2)

mmd
mmd

Reputation: 45

Thank you for your correct answer "mr LoicTheAztec";

It has developed your codes, for the use of friends;

Note:attributes $value label added:

//اضافه کردن نام ویژگی به اسم محصول
//Add attribute label name to product name

if( $product->is_type( 'variation' ) ){
        
$s ='';
$s1 = '';
foreach ($product->get_attributes() as $taxonomy => $attribute_obj ) {

 // Get the attribute label
 $attribute_label_name = wc_attribute_label($taxonomy);

 //convert to array 
 $attribute_arr = json_decode(json_encode($attribute_obj),true);
 $term_name      = get_term_by( 'slug', $attribute_arr, $taxonomy)->name;

 $s = $s . $s1 .$attribute_label_name.':'.$term_name;
 $s1 = ', ';

}

$name = $name . '(' .$s. ')';
echo '<p>' . $name. '</p>';


}

Upvotes: 0

LoicTheAztec
LoicTheAztec

Reputation: 253804

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

Upvotes: 2

Related Questions