`WP_Query()` is a powerful tool that allows you to create custom queries based on a variety of criteria, including post type, taxonomy, date, and more.
In this post, we’ll explore some if the features of `WP_query()` and how to use them to create custom queries in WordPress.
Creating a Basic Query with WP_Query()
let’s start by creating a simple query that retrieves the 10 most recent posts from your site:
$query = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => 10,
) );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// Display post content
the_title();
}
}
In this example, we’re creating a new WP_Query() object with an array of arguments that specify we want to retrieve posts of type ‘post’ and limit the results to 10 posts per page. We then loop through the retrieved posts using while ( $query->have_posts() ), calling the_post() to set up the global post object, and display the post content.
Customizing Query Parameters with WP_Query()
`Wp_Query` offers a wide range of parameters that you can use to customize your queries. Here is a few examples:
- `category_name`: Retrieve posts that belong to a specific category by name.
- `tag`: Retrive posts that have a specific author.
- `author`: Retrieve posts by a specific author.
- `post__in`: Retrieve posts by a specific set of post IDs.
For example, if you wanted to retrieve posts that belong to the ‘news’ category and have the tag ‘breaking’, you could use the following query:
$query = new WP_Query( array(
'category_name' => 'news',
'tag' => 'breaking',
) );
You can find a full list of query parameters in the official WordPress documentation.