skip to Main Content

how do you output variation attributes for an woocommerce product, where each attribute is in a seperate div?

add_action( 'woocommerce_after_shop_loop_item_title', 'display_color_attribute', 5 );
    function display_color_attribute() {
        global $product;

        if ( $product->is_type('variable') ) {
            $taxonomy = 'pa_color';
            echo '<span class="attribute-color">' . $product->get_attribute($taxonomy) . '</span>';
        }
    }

This right here output both colors on the product page seperated by a comma so for one product it could be:

<span class="attribute-color">Black, Brown</span>

What i would like is to output these two colors in two seperate div, like this:

<span class="attribute-color black">Black</span>
<span class="attribute-color brown">Brown</span>

is this doable?

2

Answers


  1. I suspect $product->get_attribute($taxonomy); returns an array so you would need to loop over it like below:

    add_action( 'woocommerce_after_shop_loop_item_title', 'display_color_attribute', 5 );
    function display_color_attribute() {
        global $product;
    
        if ( $product->is_type('variable') ) {
            $taxonomy = 'pa_color';
            $colors = $product->get_attribute($taxonomy);
            foreach ($colors as $color) {
                echo '<span class="attribute-color '. strtolower($color) .'">' . $color . '</span>';
            }   
        }
    }
    
    Login or Signup to reply.
  2. 1.By looking your code as well as based on get_attribute() details you are actually getting a comma separated string.

    2.So explode() it to convert to array and loop over it like below:

    add_action( 'woocommerce_after_shop_loop_item_title', 'display_color_attribute', 5 );
    function display_color_attribute() {
        global $product;
    
        if ( $product->is_type('variable') ) {
            $taxonomy = 'pa_color';
            $colors = explode(',',$product->get_attribute($taxonomy));
            foreach ($colors as $color) {
                echo '<span class="attribute-color '. strtolower(trim($color)) .'">' . trim($color) . '</span>';
            }   
        }
    }
    

    Reference:-

    explode()

    strtolower()

    trim()

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