Хей, имам нещо специално за теб!
Попълни имейл адрес, на който до минута ще получиш обещаното ;)
WordPress has hundreds of built-in functions that allow us to query for posts in many different ways. The main responsible for this is the WP_Query class, which provides access to practically everything – from post titles and content to author information and publication dates.
Together with The Loop, WP_Query becomes the best friend of every WP developer, thanks to its multitude of arguments and parameters that provide access for customized database queries.
Thanks to the WP_Query class, you can make various customized page-specific queries to the mySQL database, where all the posts (as well as pages, comments, users, configuration settings) of your website are stored.
As a WordPress developer (I don’t like the word “developer”), you can precisely specify the queries you send to the database using this PHP class (which is built-in by default for WP).
And here’s an example of how the code for a sample query looks like:
// WP_Query
$query = new WP_Query ([
'post_type' => 'post',
'posts_per_page' => 25,
'category_name' => 'health',
]);
In the example mentioned above, we are stating that we want all posts of the “post” type (since we can call a page, custom post type, etc.), to be displayed 25 per page and belong to the “health” category.
As I mentioned earlier, along with The Loop, WP_Query provides you with a wide range of possibilities for displaying posts on your website.
To start with your first query to the database, it is necessary to have at least some familiarity with how The Loop works.
In this tutorial, I explain more about it and the way to extract information about a specific post from the database. (link)
Based on the parameters provided in WP_Query, here’s what you can extract using The Loop:
And here’s a brief overview of how The Loop looks in WordPress:
// The Loop
if ( have_posts() ) :
while ( have_posts() ) : the_post();
// Display post content here
endwhile;
endif;
With the above example, you will access ALL posts. But what if you want to “query” only the most popular posts (with the highest number of comments), or posts from a specific category, or posts from a specific author? This is where the power of WP_Query comes into play, specifically with its arguments (also known as WP_Query args).
By utilizing different arguments, you can customize your WP_Query to retrieve specific sets of posts based on your criteria. For example, you can use the ‘orderby’ parameter to sort posts by the number of comments or the publication date, and the ‘category_name’ parameter to retrieve posts from a specific category. There are many more arguments available to tailor your query according to your needs.
// Instantiate WP_Query instance
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<h2>' . get_the_title() . '</h2>';
}
} else {
// No posts found
echo '<p> No posts found. </p>'
}
// Restore original Post Data
wp_reset_postdata();
The arguments of WP_Query inform WordPress about the specific information you want to retrieve from the database. Instead of displaying all posts (as in the example above), the arguments will set certain conditions within The Loop.
As you may have noticed in the code snippet above, we have $args
as a parameter in $the_query
. This is where you can specify your arguments.
By customizing the $args
variable, you can define conditions such as post type, category, author, sorting order, and more. These arguments allow you to tailor the query to retrieve the desired subset of posts from the database.
To achieve this, you need to provide specific parameters within an array. For example:
$args = array(
'parameter1' => 'value',
'parameter2' => 'value',
'parameter3' => 'value'
);
As I mentioned earlier, adding parameters is an important part of customizing WP_Query. Through these parameters, you can instruct WordPress to retrieve a collection of specific posts from the database.
And like most things in WordPress, here too we have ready-made parameters that you can include in your arguments.
Some commonly used parameters for WP_Query include:
'post_type'
: Specifies the post type to retrieve (e.g., ‘post’, ‘page’, ‘custom_post_type’).'category_name'
: Retrieves posts from a specific category by providing the category slug.'author_name'
: Retrieves posts from a specific author by providing the author’s username.'orderby'
: Specifies the sorting order of the retrieved posts (e.g., ‘date’, ‘title’, ‘comment_count’, ‘rand’).'posts_per_page'
: Limits the number of posts to be displayed per page.These are just a few examples, and there are many more parameters available to customize your WP_Query according to your specific needs.
I will show you some commonly encountered examples of customized WP_Query, but considering all the parameters, you can play around and see how you could optimize your query.
Most often, visitors to a website are interested in its latest publications. A common approach is to display related (by category) new articles under a given publication.
// 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 WP_Query instance
$my_query = new WP_Query( $args );
In the above example, we take the ID of the current post and retrieve its category (or categories). Then we create an array of arguments where we specify that we want the category of the displayed posts to be the same as the current post. At the same time, we exclude the current post itself from the related posts. Finally, we create a WP_Query with the provided parameters in the arguments.
If you have loyal followers, they will want to read the latest publications since they have already gone through the older ones. This is particularly relevant for a news website.
// Setting up the arguments
$arguments = array(
"date_query" => array(
array(
"year" => date( "Y" ),
"week" => date( "W" ),
)
)
);
// Instantiate WP_Query instance
$posts = new WP_Query($arguments);
By using WP_Query, you can set parameters based on the publication date of an article/post. This way, you can prevent the display of older publications.
Similarly to retrieving posts based on their publication date, you can also sort them by the number of comments. This way, you will have the most popular posts that your audience would be interested in seeing first.
// Setup arguments
$args = array(
// Order by comment count
'orderby' => 'comment_count'
);
// Instantiate WP_Query instance
$my_query = new WP_Query( $args );
Additionally, you can display the most popular posts within a specific category:
// Setup arguments
$arguments = array(
"category_name" => "fiction",
"orderby" => "comment_count",
"posts_per_page" => 5,
);
// Instantiate WP_Query instance
$posts = new WP_Query($arguments);
In the last example, you will display only 5 of the most popular posts in the “fiction” category. Of course, you can change this number as well as the category as per your requirements.
// Setup arguments
$arguments = array(
"author_name" => "author_name",
"category_name" => "fiction",
"posts_per_page" => 3,
);
// Instantiate WP_Query instance
$posts = new WP_Query($arguments);
With this short tutorial dedicated to WP_Query, I hope you have understood the power of this class and all its arguments and parameters. Customized content is becoming increasingly important in the modern web, and what better way to serve exactly what the user wants to see 🙂
Stay blond 😉