Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

woocommerce get list of attribute values

I'm using woocommerce on wordpress to create a simple shop site and I've added a couple attributes to a product. These are namely, size and color. Under size I have a variety of values including Small, Medium and Large. Same with color ie. Red, Blue, Green.

What I want to do is show these values in a dropdown. Basically just list them out so I can use the values as filters for the shop catalog page.

Any help would be great.

EDIT: I've delved into the woocommerce code and api docs and only found this code to pull the attributes.

global $woocommerce;

$attr_tax = $woocommerce->get_attribute_taxonomy_names();

foreach( $attr_tax as $tax ) {
     echo $woocommerce->attribute_taxonomy_name( $tax->attribute_name );
}

What this snippet gives me are the taxonomy slugs only, ie. pa_size and pa_color. I'm very new to woocommerce, but a search in there api docs reveals nothing about how to pull the values of these attributes.

like image 460
clueless Avatar asked Dec 10 '13 16:12

clueless


4 Answers

You can use get_terms() https://developer.wordpress.org/reference/functions/get_terms/

If you pass in pa_size or pa_color you will get back a list of terms in that taxonomy.

like image 194
Steven Jones Avatar answered Nov 02 '22 23:11

Steven Jones


Hoping this is helpful to someone:

global $product; 

// Get product attributes
$attributes = $product->get_attributes();

if ( ! $attributes ) {
    echo "No attributes";
}

foreach ( $attributes as $attribute ) {

        echo $attribute['name'] . ": ";
        $product_attributes = array();
        $product_attributes = explode('|',$attribute['value']);

        $attributes_dropdown = '<select>';

        foreach ( $product_attributes as $pa ) {
            $attributes_dropdown .= '<option value="' . $pa . '">' . $pa . '</option>';
        }

        $attributes_dropdown .= '</select>';

        echo $attributes_dropdown;
}
like image 42
runningonplants Avatar answered Nov 03 '22 00:11

runningonplants


This post was written some time ago so I don't know if Woocommerce had this method in its previous incarnations.
For anyone else looking to do this, this line is all you need.

$product->list_attributes();

This allows you to customize the order and toggle whether or not you want to display the variation in the backend,

like image 7
user5029040 Avatar answered Nov 02 '22 23:11

user5029040


In addition to @user5029040 answer, which outputs html, if you want to get an array you can use the following function.

$product->get_variation_attributes();
like image 5
Arif Avatar answered Nov 02 '22 22:11

Arif