skip to Main Content

I am trying to show attribute type and variation on my custom made minicart in woocommerce. I use WC()->cart->cart_contents[ $item ]; to get cart item object. and using wc_implode_text_attributes() to extract value from array where $variation_name return name but not attribute.

Attribute = color
variation = green , red , yellow

So I want output should be like

color:green

but the current output is only showing

green

$cart_item = WC()->cart->cart_contents[ $item ];
if( $cart_item['data']->is_type( 'variation' ) ){
    $attributes = $cart_item['data']->get_attributes();
    $variation_name = wc_implode_text_attributes( $attributes );
    var_dump( $attributes);
}

The dump result is

array(1) { [“color”]=> string(5) “green” }

So how Can I extract this dump like color:green ?

2

Answers


  1. Chosen as BEST ANSWER
    $cart_item = WC()->cart->cart_contents[ $item ];
        if( $cart_item['data']->is_type( 'variation' ) ){
        $attributes = $cart_item['data']->get_attributes();
        foreach($attributes as $attname => $variant) {
        $attribute_variation = $attname .  " : " . $variant;
        print($attribute_variation );
        }
    }
    

  2. Just replace your codes with follows –

    $cart_item = WC()->cart->cart_contents[ $item ];
    if( $cart_item['data']->is_type( 'variation' ) ){
        $attributes = $cart_item['data']->get_attributes();
        $variation_names = array();
        if( $attributes ){
            foreach ( $attributes as $key => $value) {
                $variation_names[] = $key .': '. $value;
            }
        }
        echo implode( '<br>', $variation_names );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search