Listing, Linking And Refining By Attributes In WooCommerce
I’ve been working on an e-commerce WordPress website that uses the WooCommerce plugin to power the shop and checkout process. The plugin has made the setup of the shop very simple and handles the majority of the tasks associated with an online store.
One thing that I did struggle with however was working with the attributes and allowing a user to refine their search by them. It is possible to use the default behaviour and templates but there might be a case where you want to perform a bespoke operation with these attributes. In my case I wanted to display them in the footer of a website and allow a user to click an attribute and it take them to the refined list of products.
After a bit of research I found a lot of people talking about how to get attributes for a particular product, but not how to just get all the available attributes terms in a list. As a result I ended up merging a bunch of solutions together and came up with the following code snippet.
echo '<ul>'; // get all the terms belonging to the 'material' attribute $terms = get_terms( 'pa_material', 'hide_empty=0' ); // loop through these terms and output in an unordered list foreach ($terms as $term) : // get the URL $term_link = get_term_link( $term->slug, 'pa_material' ); echo '<li><a href="'.$term_link.'" title="'.$term->name.'">'.$term->name.'</a></li>'; endforeach; echo '</ul>';
The above code will get all terms belonging to the ‘Material’ attribute and output them in an ordered list. The terms will be hyperlinked and, when clicked, will go to a refined list of products. These URL’s will be in the format:
Or, if SEO friendly permalinks aren’t activated: