Any Questions?

02476 252 345

Create a WordPress Taxonomies Search Filter Using a Tax Query

WordPress Taxonomy Filter

Video Transcript

Welcome to this weeks video blog from Mash Web Design on how to filter a WordPress loop by using a tax_query.

In the last tutorial we managed to set up our WP_Query loop and pull out posts from our “Books” custom post type. We also touched upon a very basic method of how WordPress developers can filter their results by taxonomy. You can find the previous tutorial here, we definitely recommend you complete this tutorial before continuing with this more advanced blog.

In todays video blog we will be learning how to filter our results further by using WP_Query’s tax_query, we will then be using the concepts we have learnt to create a WordPress Taxonomy search filter.

Before We Get Started

Since the last tutorial I have added two further books to our book store, “Lord of the Rings” by J R R Tolkien and “The Shining” by Stephen King. I have also added another taxonomy to our Custom Post Type for the books “Author”.

As you can see we currently have all four books showing on the front page, we will begin by heading over to our code editor and looking deeper into the WP_Query argument tax_query.

What Exactly is a WordPress Tax Query?

As we have mentioned before a WordPress tax_query enables developers to only show posts that are associated with a certain taxonomy. The tax query takes an array of arrays, by doing this developers are able to query multiple taxonomies using the “Relation” argument. We will look deeper into “Relation” argument later on in this tutorial.

Lets begin by setting up our tax query:

<?php

    $args = array(

	"order" => "asc",
	"order_by" => "title",
	"posts_per_page" => 4,
	"post_type" => "books",
	"tax_query" => array(

	    array(

                "taxonomy" => "genre", /* Taxonomy To Filter By */
                "field" => "slug", /* How To Select The Term */
                "terms" => "horror" /* The Term */

           ),

       ),

   );

...

The taxonomy argument quite simply refers to the taxonomy we want to filter by so in this case “Genre”.

The field argument refers to how we would like to select the term, we can either use “term_id”, “name” or the “slug”. I always recommend using the slug.

Lastly the “Terms” argument refers to the terms we would like to show.

If you head over to your browser and refresh you should be able to see only yours stores “Horrors” are showing.

So why use this method over the much simpler method I previewed in the previous tutorial? Quite simply as a developer you have far more control over the filter by using the tax_query this way. Lets see how easily we filter by multiple terms, let aim to show both “Horror” and “Fantasy” books.

...

"terms" => array('horror', 'fantasy')

...

Now if you head back over to your browser and refresh your page, you will be able to see that we have displayed posts from several different terms.

Using Multiple Taxonomies

Lets really put the tax_query to work by filtering the results by the “Author” as well. Lets only show fantasy novels by “J R R Tolkien”.


...

     "tax_query" => array(

         "relation" => "AND",

             array(

                 "taxonomy" => "genre",
                 "field" => "slug",
                 "terms" => array('horror', 'fantasy')

             ),

             array(

                 "taxonomy" => "author",
                 "field" => "slug",
                 "terms" => "j-r-r-tolkien",
                 "operator" => "AND"

             ),

     ),

...

By heading over to your chosen browser, you should now only be able to see the book “The Lord Of The Rings”.

By adding the “Relation” parameter we have told WP_Query that there is a logical relationship between each inner taxonomy array, we can pass in the following arguments: “AND” or “OR”.

The “Operator” allows developers to specify precisely what the purpose of the array is, we can pass in the following arguments: “IN”, “NOT IN” and “AND”.

Lets go ahead and change the “operator” argument to “NOT IN”, reload your browser and you should be able to see every book that hasn’t been written by J R R Tolkien. Before we go any further lets go ahead & switch this value back to “AND”. You should be able to see the power we have available using the tax query.

I recommend to all developers to read the WP_Query documentation on the WordPress Codex for further information.

Creating Our WordPress Taxonomies Search Filter

It is quite common to see filterable searches on eCommerce and Book website. On a lot of book websites, users have the ability to be able to filter by “Genre” as well as by “Author”. Lets use the knowledge we have learned so far regarding the tax_query, along with a range of new techniques to develop and complete this functionality.

Lets begin by going ahead & duplicating our front-page.php, lets name the page font-page-search.php, we will set this page up as our designated search results page. Ensure you have headed over to the backend of WordPress, created a results page and assigned it to our new search results template.

Creating The Form

Above our <div class=”books”> lets go ahead & open our <form>, add a submit button along with a hidden field that we will be able to validate later on. The information will be sent using the POST method and the action will be pointed towards the URL of our search results page.


    <form method="POST" action="/search-books/">

        <input type="hidden" name="submitted" value="Y">
        <input type="submit" value="Find Me A Book">

    </form>

Create Dynamic Term Drop Downs

In order for our search functionality to run properly, we will need to set up two <select> drop down menu. One for “Genre” & one for “Author”. We need to ensure that the drop down menus are fully dynamic, so we will need to dynamically retrieve the taxonomies terms. WordPress developers are able to retrieve taxonomy terms by using the WordPress function get_terms();

Retrieving Taxonomies With get_terms()

All we have to do is assign get_terms() to a variable and pass in our taxonomy name. We will then be able to loop through the object to retrieve our terms. To test our code we will var_dump() the object to see what values are available to work with.


    <form method="POST" action="/search-books/">

    <?php 

	$terms = get_terms('genre');

	if(!empty($terms) && !is_wp_error($terms)):

		echo '<select name="genre">';

			foreach($terms as $term):

				echo '<option value="'. $term->slug .'">'.$term->name.'</option>';

			endforeach;

		echo '</select>';

	endif;

	$terms = get_terms('author');

		if(!empty($terms) && !is_wp_error($terms)):

			echo '<select name="author">';

				foreach($terms as $term):

					echo '<option value="'. $term->slug .'">'.$term->name.'</option>';

				endforeach;

			echo '</select>';

		endif;

    ?>

    <input type="hidden" name="submitted" value="Y">
    <input type="submit" value="Find Me A Book">

    </form>

Head over to your browser and refresh. As you can see we can pull information out regarding the “term_id”, “name”, “slug” and “description”.

Lets run through the <select>

Reload your browser and you should be able to see both of our drop downs, submitting this form will not currently return any results. We now need to head over to our search template and add some PHP.

Lets begin by creating an if statement to check if the form has been submitted by checking to see if the hidden field returns the value “Y”. After checking the form has been successfully sent, we will then set up two variable for both our taxonomies. We will use the WordPress function esc_html() to ensure no malicious data has been passed through our search.


   <?php 

	if(!empty($_POST['submitted']) == 'Y'): 

		$genre = esc_html($_POST['genre']);
		$author = esc_html($_POST['author']);

	endif;

   ?>

We now need to alter our WP_Query to pass in our dynamic variables. Add the $genre variable inside our first array and lets add our $author variable inside our second array.


...

     "tax_query" => array(

         "relation" => "AND",

             array(

                 "taxonomy" => "genre",
                 "field" => "slug",
                 "terms" => $genre

             ),

             array(

                 "taxonomy" => "author",
                 "field" => "slug",
                 "terms" => $author,
                 "operator" => "AND"

             ),

     ),

...

Save the above code and head quickly over to our front-page.php template file, lets remove the tax_query from this template so initially it will show all books stocked in the store.

Your filterable search should now work perfectly, and return the correct books based on the data the user has entered.

This concludes this weeks video blog, if you have any questions please send them to me via the supporting comments.

Written by:

Creative Director - info@mash-webdesign.co.uk - 07541987924 - DOB: 02/1993/27

With over five years commercial experience in the web industry, Adam specialises in all things web related. Adam has a passion for CRO, ensuring that the websites he creates don't just look great but also make his clients money.

Mash Web Design