skip to Main Content

I want to show attibutes from a simple product, in cart and checkout. Just like variable products does, but there is only one attibute. See image below:

Simple product attribute walkthrough

Is this possible to achive with PHP?

I was thinking about something like using echo $product->get_attributes()

2

Answers


  1. Yes you can. Please try adding a filter as bellow,

    add_filter('woocommerce_cart_item_name', function($name, $cart_item) {
        //has attributes
        if ($cart_item['data']->is_type( 'simple' ) && $attributes = $cart_item['data']->get_attributes()) {
            $name .= " - ";
            foreach ($attributes as $att)
                $name .= $att->get_name() . " : " . implode(',', $att->get_options());
        }
        return $name;
    }, 10, 2);
    
    Login or Signup to reply.
  2. Add the follows code snippets to achieve your above task –

    function modify_woocommerce_get_item_data( $item_data, $cart_item ) {
        if( $item_data || $cart_item['data']->is_type( 'variation' ) ) return $item_data;
        if ( $cart_item['data']->is_type( 'simple' ) ) {
        $attributes = array_filter( $cart_item['data']->get_attributes(), 'wc_attributes_array_filter_visible' );
    
        foreach ( $attributes as $attribute ) {
            $values = array();
    
                if ( $attribute->is_taxonomy() ) {
                    $attribute_taxonomy = $attribute->get_taxonomy_object();
                    $attribute_values   = wc_get_product_terms( $cart_item['data']->get_id(), $attribute->get_name(), array( 'fields' => 'all' ) );
    
                    foreach ( $attribute_values as $attribute_value ) {
                        $value_name = esc_html( $attribute_value->name );
    
                        if ( $attribute_taxonomy->attribute_public ) {
                            $values[] = '<a href="' . esc_url( get_term_link( $attribute_value->term_id, $attribute->get_name() ) ) . '" rel="tag">' . $value_name . '</a>';
                        } else {
                            $values[] = $value_name;
                        }
                    }
                } else {
                    $values = $attribute->get_options();
    
                    foreach ( $values as &$value ) {
                        $value = make_clickable( esc_html( $value ) );
                    }
                }
    
                $item_data[] = array(
                    'key'   => wc_attribute_label( $attribute->get_name() ),
                    'value' => apply_filters( 'woocommerce_attribute', wpautop( wptexturize( implode( ', ', $values ) ) ), $attribute, $values ),
                );
            }
        }
        return $item_data;
    }
    add_filter( 'woocommerce_get_item_data', 'modify_woocommerce_get_item_data', 99, 2 );
    

    Codes goes to your active theme’s functions.php

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search