Retrieving results filtered by WP_Tax_Query

Retrieving results filtered by WP_Tax_Query

Online by JSC0d3
July 12, 2017 | | | 393 recognitions

In this third part of our series, after presenting the WP_Meta_Query and the WP_Date_Query Generators, we are introducing the WP_Tax_Query Generator which allows you to filter queries by taxonomies.

Retrieving results filtered by WP_Tax_Query

Filtering by taxonomies

Retrieving filtered data with WP_Query and other supported query classes is a no brainier. But for advanced filtering we may need to retrieve data assigned to a specific multiple categories, tags or any other taxonomy terms.

WordPress stores taxonomy-related data in separate database tables. wp_terms holds the term data. wp_term_relationships stores the relationships between terms (category, tag, custom) and an object (mostly posts but can be used for other objects in WordPress – like Users or Comments). wp_term_taxonomy describes the taxonomy (category, link or tag) for the entries in the wp_terms table.

To retrieve data from those tables it translates query data and conditions to SQL. But you shouldn’t write your own SQL – it’s a bad practice! WordPress will do it for you, in a secure way, with caching and other mechanisms that ensure maximum performance and utilization.

The WP_Query class retrieves taxonomy-related data using the tax_query parameter, which accepts an array. This array is handled by the WP_Tax_Query class to generate an SQL clause which in return retrieves the needed data.

In theory, we can assign taxonomies to not only Posts, but also to Comments and Users, and then filter them using the WP_Tax_Query class. But this topic is way out of the scope of this post. Maybe in the future I will write a separate post about this, let me know in the comments if you’re interested and I’ll take that into account!

Introducing the tax query generator

The WP_Tax_Query Generator is designed to help you create custom taxonomy queries, save them to your account and integrate into the main WP_Query. Use this new generator to learn the query internals, or use it as part of your daily, WordPress development workflow. You can create simple queries or even multiple advanced queries with different kind of relations between them.

 

Tax Query Parameters
Tax Query Parameters

 

This generator also supports nested queries, allowing you to combine several taxonomy queries inside each other to retrieve very complex queries.

Nested WP_Tax_Query
Nested WP_Tax_Query

Examples

In this example, we are going to filter posts in a news website with tens of thousands of posts. Let’s start with a simple example – filtering posts from the flight category.

$tax_query = array(
	array(
		'taxonomy'         => 'category',
		'terms'            => 'flight',
		'field'            => 'slug',
	),
);

Now that we got that down, let’s filter results from multiple taxonomies. We are going to filter posts from the flight category AND from the opinion section AND a video/audio Post Format. We will use the relation operator to match all filters/conditions.

$tax_query = array(
	'relation' => 'AND',
	array(
		'taxonomy'         => 'category',
		'terms'            => 'flight',
		'field'            => 'slug',
	),
	array(
		'taxonomy'         => 'section',
		'terms'            => 'Opinion',
		'field'            => 'name',
	),
	array(
		'taxonomy'         => 'post_format',
		'terms'            => array( 'post-format-video', 'post-format-audio' ),
		'field'            => 'slug',
		'operator'         => 'IN',
	),
);

Let’s create a complex filter with nested items. We are going to retrieve the above query OR all the items tagged with Nasa and airport tags.

$tax_query = array(
	'relation' => 'OR',
	array(
		'taxonomy'         => 'tags',
		'terms'            => array( 'Nasa', 'Airport' ),
		'field'            => 'name',
		'operator'         => 'AND',
	),
	array(
		'relation' => 'AND',
		array(
			'taxonomy'         => 'category',
			'terms'            => 'flight',
			'field'            => 'slug',
		),
		array(
			'taxonomy'         => 'section',
			'terms'            => 'Opinion',
			'field'            => 'name',
		),
		array(
			'taxonomy'         => 'post_format',
			'terms'            => array( 'post-format-video', 'post-format-audio' ),
			'field'            => 'slug',
			'operator'         => 'IN',
		),
	),
);

Finally, we need to insert the filter settings into our WP_Query query. We will use the $tax query array generated above, inside the tax_query argument.

// WP_Query arguments
$args = array(
	'post_type'              => array( 'post' ),
	'post_status'            => array( 'publish' ),
	'orderby'                => 'date',
	'tax_query'              => array(
		'relation' => 'OR',
		array(
			'taxonomy'         => 'tags',
			'terms'            => array( 'Nasa', 'Airport' ),
			'field'            => 'name',
			'operator'         => 'AND',
		),
		array(
			'relation' => 'AND',
			array(
				'taxonomy'         => 'category',
				'terms'            => 'flight',
				'field'            => 'slug',
			),
			array(
				'taxonomy'         => 'section',
				'terms'            => 'Opinion',
				'field'            => 'name',
			),
			array(
				'taxonomy'         => 'post_format',
				'terms'            => array( 'post-format-video', 'post-format-audio' ),
				'field'            => 'slug',
				'operator'         => 'IN',
			),
		),
	),
);

// The Query
$query = new WP_Query( $args );

In Conclusion

WordPress offers many built in tools. As in the case of the Tax Query, most of these tools are very simple to learn and offer advanced capabilities. Many of those capabilities are already integrated into our generators. We hope our tools serve your needs well!

Feel free to let us know what you think about the Tax Query in the comments.

JSC0d3's Logo
About JSC0d3

JSC0d3 is an entrepreneur, online marketer, and an employee of an IT company. When not building websites, creating content, or helping customers improve their online business, spend time with their wife and two beautiful children. Although he still feels new in WordPress, he enjoys sharing what he has learned with all of you! If you want to get in touch with him, you can do this through this website.

On the same idea

Posted by | April 1, 2019

Images are vital components of every website Before you start questioning the importance of images, just try to imagine your favorite blog or website...

Posted by | March 5, 2019

I’ve been loosely following the noise and #wpdrama surrounding Gutenberg for as long as it has been around and honestly for the most part I’ve...

Posted by | February 24, 2019

To ensure that your site ranks highly in Search Engine Result Pages (SERPs), you’ll need to make it easy for search engine ‘bots’ to explore...

Previous PostBackNext Post

Leave here an impression