By default, WordPress automatically sorts your posts from newest to oldest. Although visitors can search for specific posts using categories and tags, they might not be able to find the content they’re looking for. To curate your posts for each visitor, it can be helpful to use WordPress WP_Query.
Using WP_Query, you can customize the display of your website’s posts and pages. This PHP class enables you to simplify complex database requests. As a developer or website owner, it can help you customize pages beyond your default theme.
In this post, we’ll explain what WP_Query is. Then, we’ll show you how to use it on your WordPress website. Finally, we’ll give you some examples of ways to implement it on your blog. Let’s get started!
In WordPress, your site’s data is stored in a MySQL database. This includes everything from posts, pages, and comments, to your configuration settings.
When a visitor clicks on your website, this sends a request to your WordPress database.
Your database retrieves specific posts and pages to display them based on this query.
As a website owner, you can leverage queries to fetch specific information from your database. Although you can build SQL queries, it isn’t the most efficient way to retrieve data. This is where WP_Query comes in.
WP_Query is a PHP class that you can use to construct queries for your database. In WordPress, this is a built-in class that occurs whenever someone searches your content.
However, implementing a custom WordPress query can enable users to find specific content without searching for it. If you need to render a particular group of posts on the front end of your site, you can easily do this using a WP_Query custom post type.
For example, you might want to create a WordPress custom post type. To display these posts, you can write a specific query. Here’s the basic code structure you can use:
// WP QUERY $query = new WP_Query([ 'post_type' => 'press-release' "posts_per_page => 25, 'category_name' => 'health', ]);
This works by customizing the Loop. Essentially, the Loop is PHP code that WordPress uses to display certain posts. WordPress knows how to process and format each post based on specified criteria in your WP_Query custom post type.
WP_Query is also helpful for developers. You can customize WordPress themes using this PHP class without directly querying the database.
Now that you know about WP_Query, let’s discuss how to create your first query. This way, you can quickly and easily customize your website display!
1. Create a Loop
You’ll need to be familiar with the WordPress Loop to get started. As we mentioned earlier, the Loop is responsible for extracting post data from the database. It determines how your content is displayed according to your theme’s template files.
Based on the parameters you set, here’s what the Loop can display:
- Content from WordPress custom post types and custom fields.
- Post titles and excerpts on your homepage.
- A single post’s content and comments.
- Individual page content using template tags.
Before customizing the Loop with WP_Query, you’ll need to know the Loop structure. Here’s an example of a basic loop:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); // Display post content endwhile; endif; ?>
Let’s break down the individual parts of this loop. First, the function have_posts() will check to see if there are posts on your site. If so, the while condition continues the loop for every post. Essentially, this informs your database to display any posts on your website.
However, you might not want to display all your posts. By inserting WP_Query code into the Loop, you can enable WordPress to only render certain posts:
?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();
This contains the same basic Loop structure as if or while statements. However, there is an additional string of WP_Query.
You can customize the Loop to only display posts associated with a specific WordPress taxonomy, category, or author based on your set parameters. You could also narrow results by date, tags, custom fields, and more. In other words, when it comes to customizing the Loop with WP_Query, there are many routes you can take.
2. Use Arguments
When you structure your WP_Query, you need to include four basic elements:
- Query argument
- Query itself
- The Loop
- Post data reset
One of the most critical parts of your query is the argument (known as WP_Query args). The argument informs WordPress what data you want to retrieve from the database. Instead of displaying all of your post content, the argument will place some conditions on your loop.
You probably noticed the ($args) line in the previous example. This is where you’ll include your query argument.
To structure your WP_Query args, you’ll need to place certain parameters in an array. We’ll discuss parameters in the next section, but here’s how a basic argument looks:
$args = array( 'parameter1' => 'value', 'parameter2' => 'value', 'parameter3' => 'value' );
For example, if you want to display posts that have a ‘cooking’ tag, this is how you can code your argument:
$query = new WP_Query( array( 'tag' => 'cooking' ) );
If you don’t include a WP_Query arg, this won’t pull any content from your database. Without this information, WordPress won’t know which posts to display.
3. Set Parameters
As we mentioned earlier, setting parameters is important for customizing WP_Query. You can enable WordPress to retrieve a custom collection of posts from your database by specifying this information.
If you’re unsure which parameters to include in your argument, WordPress provides examples for many different uses. Since these are already coded for you, this can save you time and effort when building your WP_Query.
Here are some common parameters you can use:
- Posts_per_page – sets the number of posts that you want to display.
- Author – narrows down the results by one or more authors.
- Cat – specifies the categories that results should fall under.
- Tag – pulls posts that have specific tags.
- Orderby – sorts results by author, post type, date, etc.
- Order – sorts results in ascending or descending order.
- Post_type – defines whether the query should retrieve posts, pages, or custom post types.
- Post_status – specifies if posts are in-progress, scheduled, published, or deleted.
For example, you might need to display posts from a certain category. In this case, you can include the category name and slug:
$query = new WP_Query( array( 'category_name' => 'staff' ) );
This will pull posts under this WP_Query category and any children of this category.
Using different parameters, you can also show posts from a specific date. For displaying content from 9 AM to 5 PM on weekdays, this is the parameter you would use:
$args = array( 'date_query' => array( array( 'hour' => 9, 'compare' => '>=', ), array( 'hour' => 17, 'compare' => '<=', ), array( 'dayofweek' => array( 2, 6 ), 'compare' => 'BETWEEN', ), ), 'posts_per_page' => -1, ); $query = new WP_Query( $args );
The number of parameters you can use is practically limitless. By including these custom conditions in your arguments, your WP_Query can successfully present the correct data.
4. Modify Class Properties with Methods
Since WP_Query is a PHP class, it contains constants called properties. These are variables for the PHP class.
The developers at WordPress recommend not to alter WP_Query properties directly. However, you can use methods to interact with them.
Methods work similarly to functions. When you modify the methods of WP_Query, you can customize the data that is retrieved.
In the documentation for WP_Query, there are many listed functions for basic tasks. For example, including a reset_postdata() function can be an important step in writing your WP_Query. This method will reset the properties for $current_post and $post.
Here’s what that might look like:
<?php // the query $the_query = new WP_Query( $args ); ?> <?php if ( $the_query->have_posts() ) : ?> <!-- pagination here --> <!-- the loop --> <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?> <h2><?php the_title(); ?></h2> <?php endwhile; ?> <!-- end of the loop --> <!-- pagination here --> <?php wp_reset_postdata(); ?> <?php else : ?> <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p> <?php endif; ?>
Ultimately, you’ll have to use this method if you use the_post() function in your query. This ensures that the template tags use the main query’s current post.
Here are some additional methods you can use to modify your WP_Query properties:
get_posts
– retrieves a post array based on given variables.have_posts
– determines whether posts are available in the Loop.generate_postdata
– displays posts.fill_query_vars
– completes the query variables not listed in the parameters.
Based on the information you provide, you can customize your WP_Query to perform the needed function. This can be a flexible, safe way to modify class properties.
Once you learn the basics of WordPress WP_Query, you can start using it to customize your website design. Since there are various parameters you can define, the options are almost endless.
Let’s discuss some common examples of WP_Query to give you some inspiration!
1. Latest Posts in a Certain Category
Generally, online users are most interested in new content. After visitors read one of your posts, you’ll want to provide some related content. By recommending more recent posts, you can direct users to other content they might enjoy.
There are a few ways to add WordPress-related posts together, and with this WP_Query can be especially useful for websites that have time-sensitive posts. For example, visitors might read a scientific article on memory loss. Using WP_Query, you can highlight similar topics with up-to-date research:
If you want to pull the latest posts in a specific category, paste this WP_Query:
<?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 ); ?>
After editing this query with your site’s information, you can display similar posts to the one a visitor just read. This can effectively guide the user to relevant, current information without searching for it.
2. Posts Published This Week
If you have a dedicated following, readers will want to read your newest articles as soon as they’re published. When you can design your website to feature recent posts, you can provide the most relevant information.
Especially if you host a news site, you’ll need to format your posts from newest to oldest. Doing this can enable users to quickly and easily find time-sensitive content.
Using WP_Query, you can set parameters based on an article’s date. By only retrieving posts published in the past week, you can prevent users from seeing out-of-date articles:
<?php $arguments = array( "date_query" => array( array( "year" => date( "Y" ), "week" => date( "W" ), ) ) ); $posts = new WP_Query($arguments); ?>
When you customize the date_query
parameter, you can target posts published recently. Although you can include your own custom values, it can be effective to highlight articles written in the past week.
Similarly, you can promote posts that most of your audience enjoyed. By informing users that another post received a lot of engagement, it can encourage them to click on the post to find out more.
Since WordPress doesn’t keep track of your post view count, you’ll likely need to add this functionality yourself. You can do this with a plugin, but this can slow down your site.
With WP_Query, you can suggest other popular posts according to their number of comments. This makes it easy to display your most well-liked articles:
Here is the data you can use to structure your recommendations based on popularity:
<?php // Setup arguments. $args = array( // Order by comment count. 'orderby' => 'comment_count' ); // Instantiate new query instance. $my_query = new WP_Query( $args ); ?>
You can also narrow down these results based on a certain category. Simply add a parameter with your category name:
<?php $arguments = array( "category_name" => "fiction", "orderby" => "comment_count", "posts_per_page" => 5, ); $posts = new WP_Query($arguments); ?>
This will also limit the recommendations to five posts. If needed, you can edit this value with a different number.
4. Posts by the Same Author and Category
When visitors read your blog post, they may really enjoy that content. They might simply prefer the author’s writing style or the general topic.
In this case, you can use WP_Query to offer similar post recommendations. This way, readers can click on additional articles to continue reading:
To build a row of similar posts, you’ll need to implement a specific WP_Query string. This will search for blog posts on your website that have the same author and post category.
Here is the code you can use:
<?php $arguments = array( "author_name" => "john", "category_name" => "fiction", "posts_per_page" => 3, ); $posts = new WP_Query($arguments); ?>
When implementing this code, you’ll want to replace ‘john’ with the author’s name. Then, remove ‘fiction’ and include your category’s label. Finally, feel free to modify the number of post recommendations displayed on the page.
5. Author’s Yearly Posts
If you run a more prominent blog, you likely have many different authors who write posts. After someone reads one of your posts, they might want to find additional posts by that author more easily.
In this case, you can list an author’s posts from the past year. This can give visitors information about the author and a list of their previous writing:
To develop a list of an author’s yearly posts, you can use this WP_Query:
<?php // Get the year we're in. $current_year = date( 'Y' ); // Setup arguments. $args = array( // Get the author with the nicename "john". 'author' => 'john', // Get his posts from this year. 'year' => $current_year ); // Instantiate new query instance. $my_query = new WP_Query( $args ); ?>
This data will pull all the posts written by a specific author. It will also refine these results based on the current year. For instance, it won’t list any articles published over a year ago.
6. Preview Scheduled Posts
To give your audience a sneak peek of upcoming content, you can list your scheduled posts on your website. Using WP_Query, you can display the title and excerpts of your new posts.
This can help generate interest in your articles before you release them. Plus, it’s easy to implement with WP_Query:
<?php /* * Usage with Excerpts: * * <?php echo tutsplus_show_drafts(); ?> * * Usage without Excerpts: * * <?php echo tutsplus_show_drafts( false ); ?> */ function tutsplus_show_drafts( $show_excerpts = true ) { // Setup arguments. $args = array( 'post_status' => 'future', 'nopaging' => true ); // Instantiate new query instance. $my_query = new WP_Query( $args ); // Check that we have query results. if ( $my_query->have_posts() ) { // Begin generating markup. $output="<section class="pending-posts">"; // Start looping over the query results. while ( $my_query->have_posts() ) { $my_query->the_post(); // Output draft post title and excerpt (if enabled). $output .= '<div class="pending">'; $output .= '<h3 class="pending-title">' . get_the_title() . '</h3>'; $output .= get_the_title(); $output .= '</h3>'; if ( $show_excerpts ) { $output .= '<div class="pending-excerpt">'; $output .= get_the_excerpt(); $output .= '</div>'; } $output .= '</div>'; } // End generating markup. $output .= '</section>'; } else { // Let user know that nothing was found. $output="<section class="drafts-error">"; $output .= '<p>' . __( 'Nothing found', 'tutsplus' ) . '</p>'; $output .= '</section>'; } wp_reset_postdata(); return $output; } ?>
This will automatically set up a preview of your scheduled post titles. You can also include an excerpt if needed.
WP_Query provides a simpler way to perform WordPress database requests. Using this PHP class, you can customize your site’s display and offer a unique experience for each online visitor.
Here are the four ways you can use WP_Query in WordPress:
- Create a loop.
- Use query arguments.
- Set specific parameters.
- Modify class properties.
When you’ll get the hang of these WordPress WP_Query techniques, you will be able to recommend specific posts based on popularity, date, author, and more.
If you have any more questions regarding WP_Query, feel free to leave a comment down below. Make sure to use reliable WordPress hosting for top-notch site performance.