The great thing about WordPress is that not only is it highly user-friendly, but it is also very powerful. One example of WordPress’s power and versatility in action is the WP_Query class. In this guide, I will introduce you to what WP_Query is, answer a few common questions, and provide you with a quick and easy tool for creating queries.
Table of Contents
- What is WordPress Query?
- WordPress Query Use Cases
- WP Query Generator
- Setting General Parameters
- FAQ
- Summing Up
What is WordPress Query?
As one of the most important aspects of the WordPress codebase, the WP_Query class provides a way to perform complex database queries safely and simply. It determines the query for a particular page and pulls the necessary posts. In addition, it saves information about the requests it has made, thus helping optimize and troubleshoot pages.
WordPress Query Use Cases
The WordPress Query can be used for so many things. The first example below is a WP_Query for displaying posts from the music category:
<?php
// The Query
$the_query = new WP_Query( 'category_name=music' );
?>
However, that code on its own will not display the posts. To do that, we need to use the WordPress loop. For example:
<?php
// The Query
$the_query = new WP_Query( 'category_name=music' );
// The Loop
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
}
echo '</ul>';
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
?>
In this next example, WP_Query is used for displaying a list of all the posts written by a particular author this year:
<?php
// Get the year we're in.
$current_year = date( 'Y' );
// Setup arguments.
$args = array(
// Get the author with the nickname "dave".
'author' => dave,
// Get his posts from this year.
'year' => $current_year
);
// Instantiate new query instance.
$my_query = new WP_Query( $args );
?>
These examples only scratch the surface of what WP_Query. It is a powerful tool for writing advanced and complex queries. You can use it to create loops within loops, known as nested loops. WordPress developers use it in themes and plugins for displaying posts.
The WordPress Codex contains a complete list of WP_Query parameters.
WP Query Generator
Working with custom WordPress queries can be challenging, especially if you’re new to programming languages and need to implement several query methods for the post type you’re using.
A Crocoblock subscription already provides different widgets for displaying custom post types, such as the Listing Grid widget in JetEngine, Smart Posts Tiles, Smart Posts List in JetBlog, and Posts in JetElements.
However, while the Listing Grid widget/block has robust query methods that are always at hand, you cannot use custom query types for JetBlog plugin widgets or the custom posts displayed with the JetElements plugin.
To solve this problem, Crocoblock created an easy-to-use free WP Query Generator tool that allows you to create custom queries to be easily applied to the dynamic posts feed.
Let’s find out how you can use the WP Query Generator for creating custom queries.
How the WP Query Generator works
The WordPress Query generator is divided into sections dedicated to different query parameters. When you set them, they become automatically added to the Generated Query code. The more parameters you use, the longer and more complex it becomes.
When you use “meta” or “tax_query”, you can add several parameters and set the relation applied to query the posts.
Once everything is done, you will have two options for using the code in the generated Query block.
JSON
Use JSON to get the generated query in the JSON format in JetPlugins widgets. Click the Copy to Clipboard button to save the code.
Open the Elementor editing page, click “Edit” on one of the widgets that provide the ability to display posts (Smart Posts List, Smart Posts Tiles, or Posts), and here locate the Custom Query block in Content > General.
Enable the Use Custom Query option and paste the generated code in the Set custom query field. The posts will be automatically queried using the set parameters.
PHP
Use PHP to get the query arguments array and use them in your work whenever you add a WP Query to PHP.
To use the generated arguments array, click the Copy to Clipboard button and paste the code to the relevant .php file.
Setting General Parameters
When you open the WP Query Generator tool, you will be redirected to the General Parameters section. Here you will be able to set:
- Post type – here, you will have to input the post type slug, e.g., post, service, etc.
- Post status – click on the field to select the status to query the posts using it (e.g., publish, draft, etc.).
- Order – choose ASC or DESC value to sort the posts in ascending or descending order.
- Orderby – here, you can choose the parameter which will be used to set the post order (e.g., select the date parameter and ACS order to show the posts in the order of oldest to newest).
Pagination parameters
- Posts per page – type in the number of posts you want to be displayed per page (e.g., 5 to display only five posts from all the queried posts).
- Offset – use this parameter to hide some of the posts already displayed (e.g., one will hide the first post from the query from being shown).
- Paged – here, you have to define the page number where you want to show the posts (in the case you want them to be displayed on this particular page).
- Page – here, you can set the page number to be displayed on the static front page.
- Ignore sticky posts – enable this option to let the query work without considering the posts set as sticky.
Post and page parameters
You can pull specific posts in this section using their ID, slug, and title. You will also be able to exclude or include pages using IDs, slug, or get a page in which its parent is in the list or not.
There are also fields where you can add information on the post IDs to identify the posts you want to retrieve.
Author parameters
Here you can define the author by ID or name to pull the posts published by one or several authors.
Category and tag parameters
In this section, you can include the query posts from the specific categories or tags (using category ID or slug) or exclude posts by category ID, slug, or the specific tag.
For example, to retrieve posts related to the Essays category but exclude those with the Non-fiction category, you will have to add the ID of the Essays category in the Category In field and add the Non-fiction category ID in the Category, not in the field.
In this case, you will only get the posts that are included in the Essays category and don’t fall under the Non-fiction category at the same time (the posts that are categorized as Essays and Non-fiction at the same time will be excluded).
Taxonomy query parameters
This section allows using custom taxonomy terms to query the posts. Here you can add several taxonomy types and use the specific taxonomy terms to retrieve the required posts or exclude the ones you don’t want to be displayed.
Each taxonomy query (or tax_query) has a set of operators (IN, NOT IN, AND, EXISTS, NOT EXISTS) to define whether the posts with specific terms should be included or excluded.
When you add more than one tax_query, you also can select the relation between the queries:
- AND – use this to query the posts that satisfy all the set taxonomy queries.
- OR – use this to query the posts that satisfy at least one of the queries.
Meta parameters
In this section, you can use several meta keys and query posts by meta fundamental values (this option is handy regarding product post types and prices).
- To create a new meta_query, you have to add an ID for the meta field (also called custom field) or get it from the database and then input the value to use in the query method.
- In the “Compare” block, you will have the set of available operators that allow you to query the posts with values in the defined custom field that are equal, less, or more than the set value, etc. So, for example, you can query the products whose prices are higher or equal to $5 and exclude all the rest.
- If you add several meta query parameters, you can define their relationships using AND and OR operators ( they work the same as in tax_query).
Date parameters
In this block, you can use the more advanced date queries to display posts published before or after the set date.
Feel free to add several parameters using the Add Item button.
There is also a Relation block with “AND” and “OR” operators to define the time interval of the posts that are to be queried.
Misc parameters
Use this block to access additional query parameters and apply them to your posts feed.
- Has Password – here, you can set whether you want to pull the posts with or without password protection.
- Post Password – here, you can define whether you want to show only posts with a specific password.
- Comment count – show only the posts that have comments. You can specify the comments count or define whether the posts that are to be displayed should have more comments than a defined value (e.g., “>=10” will retrieve only the posts that have at least 10 comments).
- User permission – here, you can define whether the queried posts will be displayed only for users with certain permissions (in the user roles).
- Post mime type – here, you can define the post mime types to specify the types of posts to query.
FAQ
It is a class provided by WordPress. Because it is a class, you can quickly access variables, functions, and checks included in the WordPress core code. This is excellent news because it means you don’t have to write all the code yourself, making your code more reliable and efficient.
You can do this in several ways, either by modifying the main query or creating a new one.
When modifying the main query, you can either:
1) Use the pre_get_posts action hook to add a function either using a plugin or by adding the function to the theme’s functions file. By combining it with a conditional statement, you can ensure it only runs on pages that display specific types of content.
2) Use query_posts(). Don’t use this one because it is inefficient and can be an unreliable way to amend the main query. It doesn’t really amend the main query. Instead, it scraps it and starts again to re-run the main query with the changes you have made. As a result, your website will be slower and can even crash.
To create a new query, you can use one of these methods:
1) The WP_Query class is the most flexible and powerful way of creating a new query.
2) The get_posts() template tag. This is used to fetch a list of posts, for example, to display in your sidebar. To do this, it uses the WP_Query class, and you can specify which posts you want by using parameters.
3) The get_pages() template tag. This is the same as get_posts() but for pages instead of posts.
Alternatively, you can use the WP Query Generator tool in Crocoblock.
Suppress_filters prevents filters from modifying the query.
Summing Up
There you go. Not only have I given you an introduction to WP_Query. I have also introduced you to a powerful free WordPress tool for quickly and easily creating your custom WordPress queries.
It doesn’t matter if you are working with Elementor or just looking for a way to simplify your work with PHP. All you need to do is use the WP Query Generator tool and display the posts using any query type you want! The generator will create the query using your custom arguments, values, and operators in a blink of an eye.
I hope you found this guide to WordPress Query helpful.