I want to display all the available product attributes in woocommerce sidebar. According to the design and plugins that I am using, it's hard to use widget boxes here.So I chose to loop all the product attributes available and show them in the sidebar.
I tried the following methods that available on woocommerce docs,
As well as tried some stack answers as well.
global $product;
$product->get_attributes();
But I am still getting an empty array.
My sidebar is included in woocommerce archive page. How can get the attribute name and it's values?
You can use Woocommerce dedicated wc_get_attribute_taxonomies()
function in a custom shortcode function that will output the list of all product attributes.
Then you will be able to add it in a text widget on the sidebar (see at the end).
The shortcode [product_attributes]
code:
add_shortcode( 'product_attributes', 'get_product_attributes' );
function get_product_attributes() {
$output = '<ul style="list-style:none;">';
foreach( wc_get_attribute_taxonomies() as $attribute ) {
$taxonomy = 'pa_' . $attribute->attribute_name;
$term_names = get_terms( array( 'taxonomy' => $taxonomy, 'fields' => 'names' ) );
$output .= '<li><strong>' . $attribute->attribute_label . ':</strong> ' . implode( ', ', $term_names ) . '</li>';
}
return $output . '</ul>';
}
Code goes in function.php file of your active child theme (or active theme). Tested and work.
Then you will add a new text widget in your sidebar and you will paste the shortcode in the text editor to get the list of product attributes…