Explanation of the WP_Query class in WordPress

The ability to write WordPress queries to fetch custom data from a database is a very necessary skill for anyone who wants to be a professional WordPress developer . Having this knowledge will enable him to display customized content that is different from what the WordPress site displays by default on different pages.

There are several methods available in WordPress to query the database, and perhaps the easiest of these methods is the one that we will explain in today’s article, which is to create custom WordPress queries using  the WP_Query class , which saves you from using custom plugins. 

In this article, we will provide you with a deeper understanding of this important programming class in WordPress, explain its importance and use cases, and explain how to use it optimally on your site through practical examples and detailed steps.

What is WP_Query in WordPress?

WP_Query is a programming class that is very useful to WordPress developers in querying the site’s database. It is found in a file called calss-query-wp with the extension php. Inside the wp-includes folder within the root folder of any WordPress site.

This class allows developers to write custom queries to get specific information from the WordPress database. You can access this file on your site, open it with any code editor, and learn about the most important features and methods contained in it.

This class is typically used to get any type of content that meets certain conditions from the database, but it is one of developers’ favorite ways to primarily query articles from the WordPress database.

What does the word inquiry mean?

Query is a term that means communicating with the database to request data according to specific conditions from a table or a group of tables in it.

This request returns the results of the query, which are all data records that meet these conditions. There are several languages ​​to perform the query, but the most widely used and famous language is Structured Query Language (SQL). 

On a WordPress site, each page has its own query called the main query that is used to determine the content that is displayed on that page.

If you would like to modify this query according to your own needs to display different content (such as excluding posts with a specific category from display on the home page, or arranging the display of articles based on the number of comments for each article instead of the date of publication, or obtaining any other information you wish to display) You then need to write a custom query to do this.

You can customize and modify the information of any page on your site by modifying the main query on it and running another additional query to load different additional information into it – while leaving the main query as it is – or replacing the main query itself with a new one according to your requirements.

Read also: Learn about WordPress Loop and how it works in a WordPress theme

For example , if you have a page on your site that talks about e-commerce in the Kingdom of Saudi Arabia on your site and you want to show the 3 most recent posts that talk about the Kingdom at the bottom of this page, then you can write a custom query on this page to fetch the posts and display them in addition to the data that the main query brings. for this page. 

Of course, there are several ways that enable you to do this in WordPress, whether through code, or through short code , or even through some ready-made plugins. But in today’s article, we will focus on the process of overriding and customizing the main query of the page through the WP_Query class.

The WP_Query class is distinguished by allowing the developer to easily create custom queries and modify the main query of the page or write a new query to retrieve information from the database according to specific criteria and conditions.

The conditions or criteria you want are determined by the parameters passed when you create an object from this class.

What distinguishes the WP_Query programming class from other programming methods is that the developer will not have to write long SQL statements and will not need to make complex connections with the database to obtain the data he wants. All of these details can be dispensed with if the query is done using this class.

For example: If a WordPress developer wants to get all the articles that have a specific category , or those that were written by a specific writer on the site, all he needs to do is pass the name of the category or the name of the writer as a parameter for the class only, easily as follows. 

new WP_Query ( ‘category_name=food’ ) ;
new WP_Query(‘author_name=olasaleh’);

The WP_Query class has several parameters that can be passed to it when it is created that allow you to customize the query the way you want.

These parameters are considered properties or filters for the data that we want to query, such as the type of publication post_type   , the name of the author of the publication post_author , the classification of the publication category_name   , the date of publication post_date , the content of the publication the_content , or other simple properties that are stored in the global variable $post in WordPress.

Other parameters can also be passed to prepare this row as desired, such as orderby query results or other properties.

In the following paragraphs, we will list some practical examples and applications for you to understand how to create custom WordPress queries using the WP_Query class and display any custom content on your site.

Steps to use WP_Query in WordPress?

In order to be able to use this class practically on your site, you must have some basics in object-oriented programming or object-oriented programming (OOP) and the ability to modify the programming files of your site, and do not forget to take a backup copy of any file before modifying it in order to recover it in the event that anything happens. Unexpected error.

Then you must follow the following general steps: 

1- You must create an object from the WP_Query class and pass it the parameter or set of parameters that you want it to query.

2- The results of the query must be stored in a variable and it can be called any name you choose. It is preferable to use a meaningful name. 

3- You must then go through the elements of this variable (through an iterative loop) to go through all the results it returned one by one and print or display them on the site. 

4- The previous programming steps can be written in any of your site’s files that you want to display this data (mostly written in one of the template template files or the add-on file) according to the developer’s need. 

Read also: Learn about the basic structure and hierarchy of WordPress templates

Below are practical examples that show how to perform the previous steps on a WordPress site. 

Example 1: wp_query to fetch all posts with a specific category

As we mentioned in the previous paragraphs, this row can query any information you want on your site, but it is primarily used to query articles.

For example, I have a website that talks about food and cooking, and I have several articles in my website database as shown in the following image, but I want to get all the articles that have the category (food) only and display them on a dedicated page.

1- We will first move to the template folder installed on our site and create a new template file for the template used on our site inside it, named ( customfoodtemplate.php )

2- We open this file in any code editor, create a class object inside it wp_query , pass the category_name to it as a parameter, and store the results in a variable, let it be $the_query as follows: 

<?php
/* Template Name: Custom Food Template */
// The Query
$the_query = new WP_Query( ‘category_name=طعام’ );
?>

Here we set the parameter with category_name=food because we want the class to query or retrieve from the database all posts on our site whose category name is food.

3- Of course, this query alone is not enough to accomplish the requirement. After obtaining all the required posts, we now need to write a WordPress loop code that tests if there are published articles that meet the condition so that we can display them, and it repeats the execution as long as there are posts in the query result.

 Since in the previous code we temporarily stored the articles in the variable  $the_query , we will now write a code that displays the list of all these articles that were obtained   as follows: 

<?php /* Template Name: Custom Food Template */
// The Query
$the_query = newWP_Query(‘category_name=طعام’);
// Iterative loop that goes through all the posts we got
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 were obtained
}
/* Restore original Post Data */
wp_reset_postdata();
?>

Note that the WordPress loop here uses the ready-made have_posts() function as its start condition. This function checks whether there is data in the  $the_query variable   to be displayed.

If there is data then this will in turn execute the code inside the loop. In each iteration , the_post() function is called, which is a function defined in the WP_Query class that brings us the index or index of the article returned in the query ( post indexes). In every iteration of the loop, it returns to us the index or index of the next post. 

Then we will print the title of this post in a list by calling the_title() method.

Finally, if you use the_post() in your query, you will need to call the wp_reset_postdata() function after completing each query we perform to reset the query after completing its execution to the main query that was run on the currently displayed page. This function is tasked with resetting the global variable $ post to the current article in the main query.

Without this call, the main query might crash and conflict with some other queries on the page. Also, if you do not do this, any other query on the page, including the main query, may not work.

4- To review the results of the query, we will go to the site admin control panel < and choose Pages < Add New < and we will write a title for the page, let it be (Our Custom Food).

5- From the Page Properties section, we select from the drop-down list the template template  for the page to be Custom Food Template  to override the main query of the page as shown in the following image.

 

6- Now if I go to the link of this page to view it, I will get the following result on my site: 

7- We have to modify the file code Customfoodtemplate.php and display the header and footer of the page by calling the two methods get_header() at the beginning and get_footer() at the end so that it adds to the previous page the header and footer of the basic template of the site as follows:

<?php /* Template Name: Custom Food Template */
get_header();
// The Query
// Define our WP Query Parameters
$query_options = array(
‘category_name’ = > ‘Food’ ,
‘posts_per_page’ => 3,);
$the_query = new WP_Query( $query_options );
while ($the_query –> have_posts()) : $the_query –> the_post();
// Display the Post Title with Hyperlink
the_title();
// Display the Post Excerpt
the_excerpt(__(‘(more…)’));
// Repeat the process and reset once it hits the limit
old;
wp_reset_postdata();
get_footer();
?>

The results page after this modification will be as follows:

This was a simple example of using the WP_Query class with a single parameter, and there are many other options that can be used to extend the features of this class as mentioned.

You can write more advanced queries by using additional parameters or conditions within the loop, or by using nested loops (loop within a loop).

WordPress developers can also use it to develop their own plugins and themes to display and customize posts the way they want. 

Example 2: wp_query to display latest posts in WordPress

Theme developers often need to display the most recently published articles in their templates, which allows site visitors to easily find and engage with recent content published on the site. 

The most recent articles on a site are usually displayed in the site’s sidebar, or at the end of a particular post. This can be done in WordPress in several ways but for now we will focus on using an object from the WP_Query class to do this.

We will write the following code to display the titles of only the 3 most recent articles about food on our website and not all articles. Therefore, we will pass more than one parameter to the class by defining an array variable to store the parameters that we want to pass to the class as follows. 

<?php /* Template Name: Custom Food Template */
get_header();
// The Query
// Define our WP Query Parameters
$query_options = array(
‘category_name’ = > ‘Food’ ,
‘posts_per_page’ =>3,);
$the_query = newWP_Query( $query_options );
while($the_query –>have_posts()): $the_query –>the_post();
// Display the Post Title with Hyperlink
the_title();
// Display the Post Excerpt
the_excerpt(__(‘(more…)’));
// Repeat the process and reset once it hits the limit
old;
wp_reset_postdata();
get_footer();
?>

The previous code inquires about the three most recent articles on the site that have the category Food , and then displays (the title and summary of each article, these articles, and a link to More to read the full article), and the execution result is as follows: 

The code begins by defining the query parameters and stores them in a parameter array called $query_options, which contains two parameters (the name of the  category_name , and the number of requested articles posts_per_page ).

Then it passes this array as an argument to the object of the WP_Query class , after which it stores the query result in the variable $the_query and displays it through a loop as in the previous example.

Why is WP_Query better than other methods for custom queries?

WP_Query is not the only technology for creating a custom query. There are several other ways that enable you to query the WordPress database, including:

  • Short code : By writing the short code, you can obtain custom data from the database and display it on your site without having to write any programming code or modify the template files for your site.
  • query_posts() : It is a method or software function capable of changing and modifying the main query of the page. This method is not preferred by official WordPress references because it replaces the main query of the page with a completely new one, so it should not be used in developing plugins or templates.
  • pre_get_posts: It is a hook used to change the main query of the page. Although it is one of the preferred methods for modifying the main queries on the site, you cannot use it to create an independent query without calling the main query. So hey if your goal is to modify the main query of the entire page then only you can use this hook as a replacement for the WP_Query class.
  • get_posts() and get_pages(): These two functions are safe to use anywhere in the site and implicitly use the WP_Query class to perform the query. These two functions are similar in how they work and differ only in the type of content they query. The first returns only the content of posts, and the second returns only the content of pages, as is clear in their names. 

For this reason, we can consider that WP_Query in WordPress is the most comprehensive and most customizable option among the previous options, and for this reason most developers prefer it because it enables them to query everything they want from the site’s database. 


Some FAQs about WP_Query in WordPress

Below we answer the most important questions that may come to a developer’s mind about this programming class:

Q1: When do I override the main query of a page with a subquery, and when do I write a completely new main query?

The answer here depends on how you want to display your data. For example, if you want to display articles related to an article after the same article, or you want to display the top 3 most popular articles in a site sidebar, then use a subquery to group and display the data so that you display the results of both the main query and the subquery together.

While if you want to display a list of blog posts on a specific static page of your site rather than the entire body of the page, then ignore the main query completely and display the data you want using an entirely new query.

Q2: Are there any downsides to using the WP_Query class?

In theory you can safely and efficiently use the WP_Query class to query almost anything you want and any number of queries on the same page in your site.

 However, you must be careful when executing more than one query on the same page using this row, as repeated sub-queries increase the workload on your database, cause an increase in the load on the server, and slow down the page loading time.

Conclusion

The WP_Query class helps WordPress developers display custom posts or pages within the site, and enables them to perform complex queries from a database in a safe and easy way.

In today’s article, we learned about this class located within the core WordPress files, which is mainly used by developers to obtain custom content from the database (especially when developing plugins or special themes) and explained its use with practical examples.

If you have questions about how to write specific queries in WordPress using this class, leave them for us in the comments section below the article. We also suggest you check out the WordPress Codex , which is useful for any developer who wants to learn more about custom queries and about WordPress development in general.

Avatar photo
I am a young man who has been working in WordPress and e-marketing for 10 years. I would like to share my experience with you so that we can become professional in WordPress I will be happy to share the experience with you.