So far in this series, you've learned how WP_Query
is structured and what its properties and methods are. Now we're looking at the various arguments you can use with WP_Query
and how you code them.
WP_Query
has a large number of possible arguments, which makes it extremely flexible. As you can use it to query just about anything held in your wp_posts
table, it has arguments for every permutation of query you might want to run on your content.
In this tutorial, I'll look at arguments for querying taxonomy terms.
WP_Query
Before we start, let's have a quick recap on how arguments work in WP_Query
. When you code WP_Query
in your themes or plugins, you need to include four main elements:
if
and while
tags and resetting post dataIn practice, this will look something like the following:
<?php $args = array( // Arguments for your query. ); // Custom query. $query = new WP_Query( $args ); // Check that we have query results. if ( $query->have_posts() ) { // Start looping over the query results. while ( $query->have_posts() ) { $query->the_post(); // Contents of the queried post results go here. } } // Restore original post data. wp_reset_postdata(); ?>
The arguments tell WordPress what data to fetch from the database, and it's those that I'll cover here. So all we're focusing on here is the first part of the code:
$args = array( // Arguments for your query. );
As you can see, the arguments are contained in an array. You'll learn how to code them as you work through this tutorial.
There is a specific way to code the arguments in the array, which is as follows:
$args = array( 'parameter1' => 'value', 'parameter2' => 'value', 'parameter3' => 'value' );
You must enclose the parameters and their values in single quotation marks, use =>
between them, and separate them with a comma. If you get this wrong, WordPress may not add all of your arguments to the query or you may get a white screen.
Setting parameters for taxonomy terms is a little more complicated than for categories and tags since you use tax_query
. Within this argument, you write a nested array of arguments to specify the taxonomy and term using these parameters:
taxonomy
(string): taxonomyfield
(string): select taxonomy term by ('term_id
(default), 'name'
or 'slug'
)terms
(int/string/array): taxonomy term(s)include_children
(boolean): whether or not to include children for hierarchical taxonomies. Defaults to true.operator
(string): operator to test. Possible values are 'IN'
(default), 'NOT IN'
, 'AND'
, 'EXISTS'
, and 'NOT EXISTS'
.The fact that you have the operator
parameter means you don't need to choose from one of a range of available arguments to define whether you're including or excluding terms (as you do for tags and categories), but can use tax_query
for everything taxonomy-related instead.
If you want to query for multiple taxonomies, you can also use the relation
parameter before all of your arrays (one for each taxonomy) with AND
or OR
to specify whether you want to find posts with all of the terms or any of them.
This is most easily explained with some examples.
This is the simplest scenario and involves just using one nested array:
$args = array( 'tax_query' => array( array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => 'tutorial', ) ) );
The above queries for posts with the tutorial
term in the category
taxonomy. Note that you also need to use the field
parameter to identify which field you're using to identify the term, unless you're using the term ID which is the default. If you wanted to use the term ID, you'd use something like this:
$args = array( 'tax_query' => array( array( 'taxonomy' => 'category', 'terms' => '11' ) ) );
Using the ID makes it harder for you to identify what your query is looking for at a later date, but it avoids any potential problems if you think your users might edit the term slugs.
If you want to identify posts with one or more of an array of terms in the same taxonomy, you still write one nested array, but add an array of terms.
For example, to query posts with any of a list of term IDs from your taxonomy, you use:
$args = array( 'tax_query' => array( array( 'taxonomy' => 'post_tag', 'terms' => [14, 17] ) ) );
But what if you wanted to query posts with all of these terms? You'll need to use the operator
parameter inside your nested array:
$args = array( 'tax_query' => array( array( 'taxonomy' => 'post_tag', 'terms' => [14, 17], 'operator' => 'AND' ) ) );
Note that the first example actually uses the IN
operator to find posts with any of the terms, but as this is the default, you don't have to specify it in your arguments.
Another scenario is if you want to query for posts which don't have any of an array of terms in one taxonomy, which you do like this:
$args = array( 'tax_query' => array( array( 'taxonomy' => 'post_tag', 'terms' => [14, 17], 'operator' => 'NOT IN' ) ) );
Here, I've replaced the AND
operator with NOT IN
, which means WordPress will find posts without any of the terms in the array.
Note that if you prefer to use slugs instead of term IDs, you can do so with any of these scenarios. The last example would look like this:
$args = array( 'tax_query' => array( array( 'taxonomy' => 'post_tag', 'field' => 'slug', 'terms' => ['php', 'strings'], 'operator' => 'NOT IN' ) ) );
If you want to work with more than one taxonomy, you'll need to create more than one array. Let's look at the simplest example, to query posts with one term from the category taxonomy and one term from the tag taxonomy:
$args = array( 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => ['tutorial'] ), array( 'taxonomy' => 'post_tag', 'field' => 'slug', 'terms' => ['javascript'] ) ) );
Here I've written two nested arrays: one for each taxonomy, using the same arguments as I did for the examples using just one taxonomy. I've preceded these with the relation
argument. You need to include the relation
argument to tell WordPress whether it's looking for all or some of the posts output by each array. This works as follows:
'relation' => 'AND'
, WordPress will fetch the posts specified in the first array and the second array. So in the example above, only posts with both the tutorial
slug in category
and the javascript
slug in post_tag
will be queried.'relation' => 'OR'
, WordPress will fetch posts output by the first array or the second array. So in this case you'll get posts with either the tutorial
slug or the javascript
slug (or both).This is the code you'd use if you were looking for posts with either of the two slugs:
$args = array( 'tax_query' => array( 'relation' => 'OR', array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => ['tutorial'] ), array( 'taxonomy' => 'post_tag', 'field' => 'slug', 'terms' => ['javascript'] ) ) );
You can also look for more than one term in a given taxonomy by adding it to the array:
$args = array( 'tax_query' => array( 'relation' => 'OR', array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => ['guide'] ), array( 'taxonomy' => 'post_tag', 'field' => 'slug', 'terms' => ['php', 'strings'] ) ) );
By combining the relation
argument with queries and also using the operator
argument, you can create sophisticated queries. The arguments below would query posts with a term from one taxonomy but without a term from another taxonomy:
$args = array( 'orderby' => 'title', 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => ['tutorial'], 'operator' => 'NOT IN' ), array( 'taxonomy' => 'post_tag', 'field' => 'slug', 'terms' => ['php', 'math'], 'operator' => 'AND' ) ) );
Note that I've used 'relation' => 'AND'
here: if I used OR
, it would query posts with slug-two
and posts without slug-one
, rather than posts which have slug-two
but not slug-one
, which is what I'm looking for.
You could conceivably take this further to query your taxonomies' terms however you wanted: using the operator
argument in both nested queries or adding an additional nested query to query terms in another taxonomy.
It is possible for you to create nested taxonomy queries to create much more complex filters to get your posts. Support for nested taxonomies was added to WordPress core in version 4.1. It was either a lot more complicated or downright impossible to get similar results earlier.
$args = array( 'tax_query' => array( 'relation' => 'OR', array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => ['guide'], ), array( 'relation' => 'AND', array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => ['tutorial'], ), array( 'taxonomy' => 'post_tag', 'field' => 'slug', 'terms' => ['php', 'strings'], 'operator' => 'AND' ) ) ) );
The above query will select posts under the category
taxonomy with the guide
slug or posts that have the tutorial
slug under category
and have the php
, strings
slug combination under post_tag
.
tax
ArgumentYou may be wondering why I haven't included the {tax}
argument, where you simply write your argument as follows:
$args = array( 'taxonomy1' => 'slug-one' );
You may be familiar with this way of querying taxonomies if you've done it in the past, but it's now deprecated, and you shouldn't use it. So stick to tax_query
! Using tax_query
gives you a lot more flexibility anyway.
Querying taxonomies is a bit more complicated than categories and tags, as you need to get to grips with the tax_query
argument.
However, as we've seen, this is a very powerful argument that gives you a lot of scope and flexibility to query your database in whatever way you wish.
This post has been updated with contributions from Nitish Kumar. Nitish is a web developer with experience in creating eCommerce websites on various platforms. He spends his free time working on personal projects that make his everyday life easier or taking long evening walks with friends.
The Best Small Business Web Designs by DesignRush
/Create Modern Vue Apps Using Create-Vue and Vite
/Pros and Cons of Using WordPress
/How to Fix the “There Has Been a Critical Error in Your Website” Error in WordPress
/How To Fix The “There Has Been A Critical Error in Your Website” Error in WordPress
/How to Create a Privacy Policy Page in WordPress
/How Long Does It Take to Learn JavaScript?
/The Best Way to Deep Copy an Object in JavaScript
/Adding and Removing Elements From Arrays in JavaScript
/Create a JavaScript AJAX Post Request: With and Without jQuery
/5 Real-Life Uses for the JavaScript reduce() Method
/How to Enable or Disable a Button With JavaScript: jQuery vs. Vanilla
/How to Enable or Disable a Button With JavaScript: jQuery vs Vanilla
/Confirm Yes or No With JavaScript
/How to Change the URL in JavaScript: Redirecting
/15+ Best WordPress Twitter Widgets
/27 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/21 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/30 HTML Best Practices for Beginners
/31 Best WordPress Calendar Plugins and Widgets (With 5 Free Plugins)
/25 Ridiculously Impressive HTML5 Canvas Experiments
/How to Implement Email Verification for New Members
/How to Create a Simple Web-Based Chat Application
/30 Popular WordPress User Interface Elements
/Top 18 Best Practices for Writing Super Readable Code
/Best Affiliate WooCommerce Plugins Compared
/18 Best WordPress Star Rating Plugins
/10+ Best WordPress Twitter Widgets
/20+ Best WordPress Booking and Reservation Plugins
/Working With Tables in React: Part Two
/Best CSS Animations and Effects on CodeCanyon
/30 CSS Best Practices for Beginners
/How to Create a Custom WordPress Plugin From Scratch
/10 Best Responsive HTML5 Sliders for Images and Text… and 3 Free Options
/16 Best Tab and Accordion Widget Plugins for WordPress
/18 Best WordPress Membership Plugins and 5 Free Plugins
/25 Best WooCommerce Plugins for Products, Pricing, Payments and More
/10 Best WordPress Twitter Widgets
1 /12 Best Contact Form PHP Scripts for 2020
/20 Popular WordPress User Interface Elements
/10 Best WordPress Star Rating Plugins
/12 Best CSS Animations on CodeCanyon
/12 Best WordPress Booking and Reservation Plugins
/12 Elegant CSS Pricing Tables for Your Latest Web Project
/24 Best WordPress Form Plugins for 2020
/14 Best PHP Event Calendar and Booking Scripts
/Create a Blog for Each Category or Department in Your WooCommerce Store
/8 Best WordPress Booking and Reservation Plugins
/Best Exit Popups for WordPress Compared
/Best Exit Popups for WordPress Compared
/11 Best Tab & Accordion WordPress Widgets & Plugins
/12 Best Tab & Accordion WordPress Widgets & Plugins
1 /New Course: Practical React Fundamentals
/Preview Our New Course on Angular Material
/Build Your Own CAPTCHA and Contact Form in PHP
/Object-Oriented PHP With Classes and Objects
/Best Practices for ARIA Implementation
/Accessible Apps: Barriers to Access and Getting Started With Accessibility
/Dramatically Speed Up Your React Front-End App Using Lazy Loading
/15 Best Modern JavaScript Admin Templates for React, Angular, and Vue.js
/15 Best Modern JavaScript Admin Templates for React, Angular and Vue.js
/19 Best JavaScript Admin Templates for React, Angular, and Vue.js
/New Course: Build an App With JavaScript and the MEAN Stack
/10 Best WordPress Facebook Widgets
13 /Hands-on With ARIA: Accessibility for eCommerce
/New eBooks Available for Subscribers
/Hands-on With ARIA: Homepage Elements and Standard Navigation
/Site Accessibility: Getting Started With ARIA
/How Secure Are Your JavaScript Open-Source Dependencies?
/New Course: Secure Your WordPress Site With SSL
/Testing Components in React Using Jest and Enzyme
/Testing Components in React Using Jest: The Basics
/15 Best PHP Event Calendar and Booking Scripts
/Create Interactive Gradient Animations Using Granim.js
/How to Build Complex, Large-Scale Vue.js Apps With Vuex
1 /Examples of Dependency Injection in PHP With Symfony Components
/Set Up Routing in PHP Applications Using the Symfony Routing Component
1 /A Beginner’s Guide to Regular Expressions in JavaScript
/Introduction to Popmotion: Custom Animation Scrubber
/Introduction to Popmotion: Pointers and Physics
/New Course: Connect to a Database With Laravel’s Eloquent ORM
/How to Create a Custom Settings Panel in WooCommerce
/Building the DOM faster: speculative parsing, async, defer and preload
1 /20 Useful PHP Scripts Available on CodeCanyon
3 /How to Find and Fix Poor Page Load Times With Raygun
/Introduction to the Stimulus Framework
/Single-Page React Applications With the React-Router and React-Transition-Group Modules
12 Best Contact Form PHP Scripts
1 /Getting Started With the Mojs Animation Library: The ShapeSwirl and Stagger Modules
/Getting Started With the Mojs Animation Library: The Shape Module
/Getting Started With the Mojs Animation Library: The HTML Module
/Project Management Considerations for Your WordPress Project
/8 Things That Make Jest the Best React Testing Framework
/Creating an Image Editor Using CamanJS: Layers, Blend Modes, and Events
/New Short Course: Code a Front-End App With GraphQL and React
/Creating an Image Editor Using CamanJS: Applying Basic Filters
/Creating an Image Editor Using CamanJS: Creating Custom Filters and Blend Modes
/Modern Web Scraping With BeautifulSoup and Selenium
/Challenge: Create a To-Do List in React
1 /Deploy PHP Web Applications Using Laravel Forge
/Getting Started With the Mojs Animation Library: The Burst Module
/10 Things Men Can Do to Support Women in Tech
/A Gentle Introduction to Higher-Order Components in React: Best Practices
/Challenge: Build a React Component
/A Gentle Introduction to HOC in React: Learn by Example
/A Gentle Introduction to Higher-Order Components in React
/Creating Pretty Popup Messages Using SweetAlert2
/Creating Stylish and Responsive Progress Bars Using ProgressBar.js
/How to Make a Real-Time Sports Application Using Node.js
/Creating a Blogging App Using Angular & MongoDB: Delete Post
/Set Up an OAuth2 Server Using Passport in Laravel
/Creating a Blogging App Using Angular & MongoDB: Edit Post
/Creating a Blogging App Using Angular & MongoDB: Add Post
/Introduction to Mocking in Python
/Creating a Blogging App Using Angular & MongoDB: Show Post
/Creating a Blogging App Using Angular & MongoDB: Home
/Creating a Blogging App Using Angular & MongoDB: Login
/Creating Your First Angular App: Implement Routing
/Persisted WordPress Admin Notices: Part 4
/Creating Your First Angular App: Components, Part 2
/Persisted WordPress Admin Notices: Part 3
/Creating Your First Angular App: Components, Part 1
/How Laravel Broadcasting Works
/Persisted WordPress Admin Notices: Part 2
/Create Your First Angular App: Storing and Accessing Data
/Persisted WordPress Admin Notices: Part 1
/Error and Performance Monitoring for Web & Mobile Apps Using Raygun
/Using Luxon for Date and Time in JavaScript
7 /How to Create an Audio Oscillator With the Web Audio API
/How to Cache Using Redis in Django Applications
/20 Essential WordPress Utilities to Manage Your Site
/Beginner’s Guide to Angular 4: HTTP
/Rapid Web Deployment for Laravel With GitHub, Linode, and RunCloud.io
/Beginners Guide to Angular 4: Routing
/Beginner’s Guide to Angular 4: Services
/Beginner’s Guide to Angular 4: Components
/Creating a Drop-Down Menu for Mobile Pages
/Introduction to Forms in Angular 4: Writing Custom Form Validators
/10 Best WordPress Booking & Reservation Plugins
/Getting Started With Redux: Connecting Redux With React
/Getting Started With Redux: Learn by Example
/Getting Started With Redux: Why Redux?
/Understanding Recursion With JavaScript
/How to Auto Update WordPress Salts
/How to Download Files in Python
/Eloquent Mutators and Accessors in Laravel
1 /10 Best HTML5 Sliders for Images and Text
/Creating a Task Manager App Using Ionic: Part 2
/Creating a Task Manager App Using Ionic: Part 1
/Introduction to Forms in Angular 4: Reactive Forms
/Introduction to Forms in Angular 4: Template-Driven Forms
/24 Essential WordPress Utilities to Manage Your Site
/25 Essential WordPress Utilities to Manage Your Site
/Get Rid of Bugs Quickly Using BugReplay
1 /Manipulating HTML5 Canvas Using Konva: Part 1, Getting Started
/10 Must-See Easy Digital Downloads Extensions for Your WordPress Site
/22 Best WordPress Booking and Reservation Plugins
/Understanding ExpressJS Routing
/15 Best WordPress Star Rating Plugins
/Creating Your First Angular App: Basics
/Inheritance and Extending Objects With JavaScript
/Introduction to the CSS Grid Layout With Examples
1Performant Animations Using KUTE.js: Part 5, Easing Functions and Attributes
Performant Animations Using KUTE.js: Part 4, Animating Text
/Performant Animations Using KUTE.js: Part 3, Animating SVG
/New Course: Code a Quiz App With Vue.js
/Performant Animations Using KUTE.js: Part 2, Animating CSS Properties
Performant Animations Using KUTE.js: Part 1, Getting Started
/10 Best Responsive HTML5 Sliders for Images and Text (Plus 3 Free Options)
/Single-Page Applications With ngRoute and ngAnimate in AngularJS
/Deferring Tasks in Laravel Using Queues
/Site Authentication in Node.js: User Signup and Login
/Working With Tables in React, Part Two
/Working With Tables in React, Part One
/How to Set Up a Scalable, E-Commerce-Ready WordPress Site Using ClusterCS
/New Course on WordPress Conditional Tags
/TypeScript for Beginners, Part 5: Generics
/Building With Vue.js 2 and Firebase
6 /Best Unique Bootstrap JavaScript Plugins
/Essential JavaScript Libraries and Frameworks You Should Know About
/Vue.js Crash Course: Create a Simple Blog Using Vue.js
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 5.5 API
/API Authentication With Node.js
/Beginner’s Guide to Angular: Routing
/Beginners Guide to Angular: Routing
/Beginner’s Guide to Angular: Services
/Beginner’s Guide to Angular: Components
/How to Create a Custom Authentication Guard in Laravel
/Learn Computer Science With JavaScript: Part 3, Loops
/Build Web Applications Using Node.js
/Learn Computer Science With JavaScript: Part 4, Functions
/Learn Computer Science With JavaScript: Part 2, Conditionals
/Create Interactive Charts Using Plotly.js, Part 5: Pie and Gauge Charts
/Create Interactive Charts Using Plotly.js, Part 4: Bubble and Dot Charts
/Create Interactive Charts Using Plotly.js, Part 3: Bar Charts
/Awesome JavaScript Libraries and Frameworks You Should Know About
/Create Interactive Charts Using Plotly.js, Part 2: Line Charts
/Bulk Import a CSV File Into MongoDB Using Mongoose With Node.js
/Build a To-Do API With Node, Express, and MongoDB
/Getting Started With End-to-End Testing in Angular Using Protractor
/TypeScript for Beginners, Part 4: Classes
/Object-Oriented Programming With JavaScript
/10 Best Affiliate WooCommerce Plugins Compared
/Stateful vs. Stateless Functional Components in React
/Make Your JavaScript Code Robust With Flow
/Build a To-Do API With Node and Restify
/Testing Components in Angular Using Jasmine: Part 2, Services
/Testing Components in Angular Using Jasmine: Part 1
/Creating a Blogging App Using React, Part 6: Tags
/React Crash Course for Beginners, Part 3
/React Crash Course for Beginners, Part 2
/React Crash Course for Beginners, Part 1
/Set Up a React Environment, Part 4
1 /Set Up a React Environment, Part 3
/New Course: Get Started With Phoenix
/Set Up a React Environment, Part 2
/Set Up a React Environment, Part 1
/Command Line Basics and Useful Tricks With the Terminal
/How to Create a Real-Time Feed Using Phoenix and React
/Build a React App With a Laravel Back End: Part 2, React
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 9 API
/Creating a Blogging App Using React, Part 5: Profile Page
/Pagination in CodeIgniter: The Complete Guide
/JavaScript-Based Animations Using Anime.js, Part 4: Callbacks, Easings, and SVG
/JavaScript-Based Animations Using Anime.js, Part 3: Values, Timeline, and Playback
/Learn to Code With JavaScript: Part 1, The Basics
/10 Elegant CSS Pricing Tables for Your Latest Web Project
/Getting Started With the Flux Architecture in React
/Getting Started With Matter.js: The Composites and Composite Modules
Getting Started With Matter.js: The Engine and World Modules
/10 More Popular HTML5 Projects for You to Use and Study
/Understand the Basics of Laravel Middleware
/Iterating Fast With Django & Heroku
/Creating a Blogging App Using React, Part 4: Update & Delete Posts
/Creating a jQuery Plugin for Long Shadow Design
/How to Register & Use Laravel Service Providers
2 /Unit Testing in React: Shallow vs. Static Testing
/Creating a Blogging App Using React, Part 3: Add & Display Post
/Creating a Blogging App Using React, Part 2: User Sign-Up
20 /Creating a Blogging App Using React, Part 1: User Sign-In
/Creating a Grocery List Manager Using Angular, Part 2: Managing Items
/9 Elegant CSS Pricing Tables for Your Latest Web Project
/Angular vs. React: 7 Key Features Compared
/Creating a Grocery List Manager Using Angular, Part 1: Add & Display Items
New eBooks Available for Subscribers in June 2017
/Create Interactive Charts Using Plotly.js, Part 1: Getting Started
/The 5 Best IDEs for WordPress Development (And Why)
/33 Popular WordPress User Interface Elements
/New Course: How to Hack Your Own App
/How to Install Yii on Windows or a Mac
/What Is a JavaScript Operator?
/How to Register and Use Laravel Service Providers
/
waly Good blog post. I absolutely love this…