1
votes

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,

  1. get_attribute()
  2. get_attributes()
  3. get_variation_attributes()

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?

1
Have you load your content on any specific hook. Please check by using var_dump($product);dineshkashera
Please try by using $product_id = 10;$WC_Product = new WC_Product($product_id); $var = $WC_Product->get_attributes( );dineshkashera
@dineshkashera It returns some product objects sir. If you want to visualize I can add the value to the questionRamesh
@dineshkashera I want to show all the product attributes in the sidebar. When user clicks one of them I have to filter the products and give the result. $WC_Product = new WC_Product($product_id); this sounds like accessing a single productRamesh

1 Answers

3
votes

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…

enter image description here