How To Use WP_Query Class In WordPress?



What is WP_Query?

WP_Query is a powerful PHP class in WordPress that allows you to construct custom queries to the dataset to retrieve posts and other content and render them on the page. It provides a flexible and efficient way to interact with the database and fetch content based on various criteria.


A short note on WP_Query

You might have known that WordPress stores all your website data like posts, pages, comments, or settings in the MySQL database.

So, for anyone who visits your website, a request is immediately sent to this database, retrieving the requested data whether it is posts or pages to display on your screen.

But you must surprised to know that with the help of WP_Query, you can create queries that can help you to retrieve specific information from your database. So whenever someone searches for your content, WordPress uses this built-in class.

No doubt, you can still use SQL to write all these queries, but it is quite difficult and not the easiest way to do it. On the other hand, WP_Query is much easier.

WP_Query is so helpful that you can create custom queries to display specific content on yuor website without the visitor having to search for it.

In short, WP_Query is a tool that makes it easier for developers to control what content gets displayed on WordPress sites and how it looks, without needing to write complicated code.

Suppose you create a special type of content in WordPress called a “blog”. To show these “blog” posts on your site, you can write a special query using WP_Query.

// WP QUERY
$query = new WP_Query([
'post_type' => 'blog', // Type of content
'posts_per_page' => 6, // Number of posts to show
'category_name' => 'Entertainment' // Category filter
]);

Now to display the requested Query, WP_Query provides shortcuts and built-in functions that help you to customize the Loop. The Loop is a bit of PHP code that WordPress uses to display posts on a page.

WordPress processes and formats each post according to the criteria you set in WP_Query (like the type of post, number of posts, and category).

This powerful tool helps developers easily customize how WordPress themes display content without having to write complex database queries


WPOven Dedicated Hosting

How you can utilize WP_Query?

Now you know what is WP_Query and What exactly it does. Let us check out different case scenarios you can utilize this powerful tool.

1. Create Loop in WP_Query

First, you should understand what Loop is. It is a part of WordPress which is highly responsive for fetching post data from the data and displays it on your website. It mainly focuses on deciding how your content looks based on your theme’s templates.

What the Loop Can Show on the website?

Depending on the settings you choose, the Loop can display:

  • Custom post types and custom fields
  • Post titles and short descriptions on your homepage
  • A single post’s content and comments
  • Content of individual pages using template tags

For your better understanding, below is a simple structure of Loop.

Basic Loop Example

<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post();
// Display post content
endwhile;
endif;
?>

  • Here, the have_posts() function checks if there are any posts available.
  • while ( have_posts() ) : the_post();: If there are posts, this loop will run for each post and display its content.

Customizing the Loop with WP_Query

Sometimes, you don’t want to display all your posts. You can use WP_Query to customize what gets shown:

<?php
// The Query
$the_query = new WP_Query( $args );

// 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();
?>

How This Custom Loop Works

  • Setting Up the Query: $the_query = new WP_Query( $args ); creates a custom query based on the parameters you set (like post type, category, etc.).
  • Running the Loop: if ( $the_query->have_posts() ) { ... } checks if there are posts that match your query. If there are, it displays each post’s title in a list.
  • Resetting Post Data: wp_reset_postdata(); ensures that the original post data is restored after the custom loop runs.

Customization Options

With WP_Query, you can:

  • Show posts from a specific category, author, or date range
  • Display posts with certain tags or custom fields

2. WP_Query Arguments

When you want to get specific posts from your WordPress site, you need to create WP_Query and for that, you need to include four basic parts:

  • Query Argument: Tells WordPress what data to retrieve.
  • The Query: Uses the argument to fetch the data.
  • The Loop: Processes and displays each post.
  • Post Data Reset: Resets the data after the loop runs.

But one of the most essential components of WP_Query is the argument (often called WP_Query args) which is responsible for extracting the specific post that you want to get from the database.

It is so important that Instead of showing all posts, the argument sets conditions to show only certain posts.

Example of an Argument

  • The $args Line: This is where you include your query argument.
  • Structure: You put certain parameters in an array. Here’s a basic example,

$args = array(
'parameter1' => 'value',
'parameter2' => 'value',
'parameter3' => 'value'
);

Specific Example

If you want to display posts with the tag ‘WordPress Errors’, you would set up your query argument like this:

$query = new WP_Query( array( 'tag' => 'WordPress Errors' ) );

Why the Argument is Essential

  • No Argument, No Content: If you don’t include a WP_Query arg, WordPress won’t know which posts to display. Your query will not fetch any content from the database.

3. Set WP_query parameters

Parameters are something that makes WP_Query useful and powerful. With the variety of them available it has become easy for anyone to filter out the database searches.

For example, when you want to show specific posts on your WordPress site, you use WP_Query and to make sure you get the right post, you can set parameters. You might have another question in your mind What are the Parameters?

Well, Parameters are just like instructions that tell WordPress what kind of posts to get from the database.

Examples of Common Parameters

Here are some common parameters you can use:

  • cat: Displays posts from specific categories.
  • author: Shows posts by one or more specific authors.
  • post_status: Shows posts that are in progress, scheduled, published, or deleted.
  • orderby: Sorts posts by author, post type, date, etc.
  • posts_per_page: Sets the number of posts to display.
  • tag: Shows posts with specific tags.
  • order: Sorts posts in ascending or descending order.
  • post_type: Defines whether to show posts, pages, or custom post types.

How to Use Parameters

If you want to show posts from a certain category, you can use the category_name parameter. Here’s an example:

$query = new WP_Query( array( 'category_name' => 'WordPress' ) );

This will show all posts in the “staff” category and any subcategories.

More Complex Example

In this example, we demonstrate how you can utilize multiple values in different arguments to create a complex and customized query to fetch the exact posts you want.

We’ll retrieve posts that are in specific categories, have certain tags, are written by specific authors, and are sorted by date in descending order.

$args = array(
'category__in' => array(5, 10), // Categories with IDs 5 and 10
'tag__in' => array('featured', 'popular'), // Posts tagged with 'featured' or 'popular'
'author__in' => array(1, 2), // Authors with IDs 1 and 2
'orderby' => 'date', // Order by date
'order' => 'DESC', // In descending order
'posts_per_page' => 10 // Limit to 10 posts
);

$query = new WP_Query($args);

// The Loop
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
// Display post content
the_title('<h2>', '</h2>');
the_excerpt();
}
} else {
// No posts found
echo 'No posts found';
}

// Restore original Post Data
wp_reset_postdata();

  • category__in: Helps to specify that we want posts from categories with IDs 5 and 10.
  • tag__in: Specifies that we want posts tagged with either ‘featured’ or ‘popular’.
  • author__in: Specifies that we want posts by authors with IDs 1 and 2.
  • orderby: Specifies that we want to order the posts by the date they were published.
  • order: Specifies that we want the posts in descending order (newest first).
  • posts_per_page: Limits the number of posts retrieved to 10.

4. Modify Objects with Methods and Class Properties

In WordPress, WP_Query is a special PHP class used to retrieve posts from the database. Think of it as a tool that helps you get the exact posts you want to show on your website.

What Are Class Properties and Methods?

In PHP, a class can have properties (like variables) and methods (like functions). Here’s a simple way to understand them:

  • Properties: These are like containers that hold information. In context to WP_Query, properties might include things like the list of posts or the number of posts found.
  • Methods: These are like tools or actions you can perform. In WP_Query, methods can help you check if there are posts, get the title of a post, or reset the query.

Can you Change Properties Directly?

No, you cannot change properties Directly, even Developers also highly discourage this, But you can use Methods alternatively.

Methods are just like official tools or commands that help you to follow the right way. These are exactly what works like the functions, when you make certain changes in methods of WP_Query, you can also customize the data that is fetched.

Example of Using Methods in WP_Query

In this example, a reset_postdata() function can be a critical step in writing your WP_Query. This method will reset the properties for $current_post and $post.

<?php
// Create a new query with specific arguments
$the_query = new WP_Query(array(
'post_type' => 'post',
'posts_per_page' => 5,
'category_name' => 'news',
));
?>

<?php if ($the_query->have_posts()) : ?>
<!-- Display the posts -->
<?php while ($the_query->have_posts()) : $the_query->the_post(); ?>
<h2><?php the_title(); ?></h2>
<p><?php the_excerpt(); ?></p>
<?php endwhile; ?>
<!-- Reset the post data to avoid conflicts -->
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>

Breakdown:
  • Creating a Query:
    • $the_query = new WP_Query($args);: It creates a new WP_Query object with the arguments you provided.
  • Checking for Posts:
    • if ($the_query->have_posts()): It checks if there are any posts to show based on your query.
  • Looping Through Posts:
    • while ($the_query->have_posts()) : $the_query->the_post();: It sets up the post data so you can display it.
  • Displaying Posts:
    • the_title(); and the_excerpt();: It displays the title and excerpt of the current post.
  • Resetting Post Data:
    • wp_reset_postdata();: It resets the global post data to the main query’s post. This is important to avoid messing up other parts of your page.

Common Methods You Can Use

Here are some common methods in WP_Query that you can use to work with your query:

  • get_posts:
    • What It Does: Retrieves a list of posts.
    • Example:phpCopy code$posts = get_posts(array('category' => 'news'));
  • have_posts:
    • What It Does: Checks if there are any posts to display.
    • Example:phpCopy codeif ($the_query->have_posts()) { // There are posts to show }
  • the_post:
    • What It Does: Sets up the current post data.
    • Example:phpCopy code$the_query->the_post();
  • fill_query_vars:
    • What It Does: Completes missing query details.
    • Example:phpCopy code$the_query->fill_query_vars($args);

By providing WP_Query with the right information, you can customize it to perform different tasks. This method is a flexible and safe way to adjust the class properties.


WP_Query Vs query_posts(): Which one is preferable?

Below is a detailed comparison table of WP_Query vs. query_posts() in WordPress, including some of the main points that can help you understand why WP_Query is generally preferred over query_posts():

FeatureWP_Queryquery_posts()
PurposeCreate custom queries for retrieving posts from the database.Modify the main query on the page (not recommended for general use).
Main UsageIdeal for creating new queries and displaying posts in a custom way.Generally used to alter the main query but is not recommended.
Recommended UseYes, it is the recommended way to fetch and display posts.No, it’s best to avoid using this function inside the main Loop, plugins, and themes.
Effect on Main QueryDoes not affect the main query. You can run custom queries without changing the main Loop.Completely overrides the main query, which can cause conflicts or unexpected results.
Resetting Post DataUse wp_reset_postdata() to restore the original query after running a custom query.No equivalent function, which means you may have to manually restore the main query’s post data.
Handling Multiple QueriesCan handle multiple queries and is designed for complex scenarios.Handles only one query and changes the main query, which can be problematic for multiple queries.
Performance ImpactGenerally better for performance since it does not alter the main query.Can be less efficient and may cause issues due to its impact on the main query.
Custom Query Examples$custom_query = new WP_Query(array('post_type' => 'post', 'posts_per_page' => 5));query_posts(array('post_type' => 'post', 'posts_per_page' => 5));
Resetting Data Example<?php wp_reset_postdata(); ?>No reset function, a manual reset is needed if changes are made to the main query.
Ease of UseEasy to use with built-in methods and functions for querying posts and pages.Less straightforward and can lead to issues if not used carefully.
WP_Query Vs query_posts()

WPOven Dedicated Hosting

Some Examples of WP_Query Usage

To better understand WP_Query and its practical usage, check out some of the Examples given below:

1. Show the Latest Posts Published this Week

If you have a good user base or a decent amount of web traffic, it means your visitors like your content and would want to read the latest articles published on your site.

While designing your website, you can feature recent posts in a dedicated section of the webpage. Thankfully, with WP_Query, you can easily find posts based on date parameters. Let us see how.

<?php
$arguments = array(
"date_query" => array(
array(
"year" => date( "Y" ),
"week" => date( "W" ),
)
)
);
$posts = new WP_Query($arguments);
?>

In this example, we create a WP_Query to find posts published in the current week. We use a special part of WP_Query called date_query to specify our search criteria.

The main purpose of the query was to find posts published during the current week. And for that, we used the date_query parameter to search for posts based on dates. It takes an array of date-related arguments.

So, when you customize the date_query parameter, you can fetch and display posts that have been published recently. However, you are also free to specify custom values to make the query more effective and to highlight the latest articles written in the past week.


2. Show the Latest Post in Specific Category

Your website visitors might often look for the newest information and to increase engagement and page views, it is a good practice to suggest some more related posts they might like.

Although, there are many ways you to link related posts in WordPress WP_Query is one the efficient ways to do this. Especially a great way for the website that always post up-to-date content.

For example, if someone reads an article about WordPress Errors, WP_Query can help show other similar and recent articles.

So, if you want to fetch the latest posts in a specific category, use this WP_query, and make little edits that include your site information :

<?php

// Get the current post id.
$current_post_id = get_the_ID();

// Get the current post's category (first one if there's more than one).
$current_post_cats = get_the_category();
$current_post_first_cat_id = $current_post_cats[ 0 ]->term_id;

// Setup arguments.
$args = array(
// Get category's posts.
'cat' => $current_post_first_cat_id,
// Exclude current post.
'post__not_in' => array( $current_post_id )
);

// Instantiate new query instance.
$my_query = new WP_Query( $args );

?>


3. Show the posts by the Same Author and in the same Category

It is highly possible that if the visitor enjoys your content, they might like the author’s views, writing style, and perception.

For this, you can use WP_Query to suggest your readers similar posts written by the same author. The query will search for the posts written by the same author for that same category as the current post.

For this, we have to create a specific WP_Query string, which will look out for posts with similar authors and the same category.

Here is the code:

<?php
$arguments = array(
"author_name" => "Rahul",
"category_name" => "WordPress",
"posts_per_page" => 3,
);
$posts = new WP_Query($arguments);
?>

In the above code, you need to replace “Rahul” with the author’s name and “WordPress” with the category name.


4. Show your most popular Posts

Just like the Latest or Recent posts you have displayed for your readers. you might also like to show posts on topics that your readers like and engage a lot. To achieve this, you can use the orderby parameter and pass it to the comment_count argument.

<?php
$arguments = array(
"category_name" => "WordPress Errors",
"orderby" => "comment_count",
"posts_per_page" => 5,
);
$posts = new WP_Query($arguments);
?>

The above WP_Query will look for posts in the “WordPress Errors” category and filter the results by the number of comments each post has.

The output will display five posts with the most comments, in descending order from left to right, starting with the post with the highest engagement and ending with the lowest.


Conclusion

Now you have witnessed, how powerful WP_Query is and How it makes it easy for you to perform database requests in WordPress. Also, provide you the flexibility to customize your site and provide a unique experience for visitors.

To use WP_Query, you can:

  • Create a Loop: Display your posts.
  • Use Query Arguments: Customize your searches.
  • Set Specific Parameters: Filter your results.
  • Modify Class Properties: Adjust query results with methods.

If you have mastered all these techniques, you will be able to easily recommend specific posts based on various factors like popularity and date.

This technique helps to increase the user’s engagement, enhance user experience, and also help your loyal visitors to find more relevant content.

If you still have doubts regarding WP_Query or would like to add more pieces of content that we might have missed. Please do let us know in the comment section below.


Leave a Reply

Your email address will not be published. Required fields are marked *