Listing, Linking And Refining By Attributes In WooCommerce

February 21st, 2013 - Posted by Steve Marks to (X)HTML / CSS, MySQL, PHP, Web Development.

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>';

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:

This entry was posted on Thursday, February 21st, 2013 at 12:31 pm by +Steve Marks and is filed under (X)HTML / CSS, MySQL, PHP, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.

Fear not, we won't publish this

Comments (5)
  1. @Gabriel – You put this code where you want the list of attributes to be output. So, for example, if you wanted to output them on your home page, you’d put the code in your home page file.

  2. Gabriel says:

    Hi Steve,

    I have the same question as below. I mean, which file should I copy this code? create a new file? or copy this code at function.php? Thanks in advance

  3. @Erkan – You put it in the place in your theme where you want to output the attributes. For me it was the footer but it can be anywhere.

  4. Erkan says:

    where do we put this code?

  5. It took me forever to find this! This is EXACTLY what I needed! Thank you!