Stanley Ngumo
Stanley Ngumo

Reputation: 4239

Getting all the product attributes and their terms in WooCommerce

I have researched this all day but cant seem to get a straight answer how can I get the set product attributes along with the configured terms for each?

This is what I have now

//get the  terms
$attribute_taxonomies = wc_get_attribute_taxonomies();
$taxonomy_terms = array();

if ( $attribute_taxonomies ) {
    foreach ($attribute_taxonomies as $tax) {
        
        //dont know what to add here
    }
}

var_dump($taxonomy_terms);

Upvotes: 4

Views: 5792

Answers (2)

B_Sharp
B_Sharp

Reputation: 11

First check the wc_get_attribute_taxonomies() function with var_dump().

Upvotes: -1

LoicTheAztec
LoicTheAztec

Reputation: 253784

Here below you will get a list of all product attributes and their respective term names:

echo '<ul>';
// Loop through WooCommerce registered product attributes
foreach( wc_get_attribute_taxonomies() as $values ) {
    // Get the array of term names for each product attribute
    $term_names = get_terms( array('taxonomy' => 'pa_' . $values->attribute_name, 'fields' => 'names' ) );
    echo '<li><strong>' . $values->attribute_label . '</strong>: ' . implode(', ', $term_names);
}
echo '</ul>';

If you prefer to get an array of the WP_terms objects, you will use:

// Get the array of the WP_Terms Object for the each product attribute
$terms = get_terms( array('taxonomy' => 'pa_' . $values->attribute_name );

That will allow use a foreach loop to get what you want from each term…

Upvotes: 4

Related Questions