Search code examples
phpwordpresswoocommerceproductcustom-taxonomy

List all WooCommerce product attribute names


Does Woocommerce have a short way of listing the attribute names outside of the main Woocomerce templates ie: single-product or product-archive?

This code almost gives me the desired result it will output my 4 attribute titles but repeats the attribute name for each product. all I need is output a list of my attribute names.

$query_args = array(
        'status'    => 'publish',
        'limit'     => -1,
    );
    foreach( wc_get_products($query_args) as $product ){
        foreach( $product->get_attributes() as $taxonomy => $attribute ){
            $attribute_name = get_taxonomy( $taxonomy )->labels->singular_name;
            foreach ( $attribute->get_terms() as $term ){
               echo '<li class="pa-filter-item"><a href="">' . $attribute_name . '</a></li>';
            }
        }
    }

The aim is to output a list of attribute names that will be used to create filter to allow the terms to be filtered inside a custom template page and not a Woocommerce page.


Solution

  • If you are not using custom attributes that can be set on a single product, you can get all your product attribute taxonomy objects using wc_get_attribute_taxonomies() function like:

    foreach ( wc_get_attribute_taxonomies() as $attribute ) {
        echo '<li class="pa-filter-item"><a href="">' . $attribute->attribute_label . '</a></li>';
    }
    

    Or you can use a custom WPDB query:

    global $wpdb;
    
    $attribute_labels = $wpdb->get_col( "SELECT attribute_label FROM {$wpdb->prefix}woocommerce_attribute_taxonomies WHERE attribute_name != '' ORDER BY attribute_name ASC;" );
    
    foreach ( $attribute_labels as $attribute_label ) {
        echo '<li class="pa-filter-item"><a href="">' . $attribute_label . '</a></li>';
    }