How To Create WordPress Custom Queries with WP_Query?

WordPress custom queries are very powerful tool. If you want to display on your index.php or single.php file other content different from what the WordPress shows by default, just create WordPress custom queries using WP_Query. For those that don’t know, WP_Query is a class that allows you to create WordPress custom queries and retrieve your posts according to criteria defined via the parameter to the constructor of this class.

To use this application you must store it in a variable and use that object in WordPress loop. In this tutorial I will show you some great examples on how to use WordPress custom queries or WP_Query in your own WordPress projects.

WordPress Custom Queries Examples

This class can be configured as desired, and there are many possibilities available to you, here are some of WordPress custom queries examples I find most useful:

Example 1: Select all posts

$query = new WP_Query(array('post_type' => 'post'));

Example 2: Select all posts and all pages

$query = new WP_Query(array('post_type' => array('post', 'page')));

Example 3: Select latest 5 posts

$query = new WP_Query(array('post_type' => 'post', 'posts_per_page' => 5));

Example 4: Select latest 5 posts from one or more categories

$query = new WP_Query(array('posts_per_page' => 5, 'category_name' => 'type-your-category-name'));

Example 5: You can also use one or more IDs or even categories slug to select posts from your WordPress database.

$query = new WP_Query('posts_per_page' => 5, 'cat=1,3,10,11,25,32');
$query = new WP_Query('posts_per_page' => 5, 'category_name=windows,android,ios,');

Example 6: Select the custom post type “windows” sorted by title in descending order

$query = new WP_Query(array('post_type' => 'windows', 'orderby' => 'title', 'order' => 'DESC'));

Example 7: Select all the posts that have not specified ID inside query

$query = new WP_Query(array('post__not_in' => array(2, 5, 12, 14, 20)));

Example 8: Select all the posts that have the specified ID inside query

$query = new WP_Query(array('post__in' => array(2, 5, 12, 14, 20 )));

There you go, those was some of queries you will most probably use, if you have any other suggestions leave them in comment section below. Also I strongly suggest you to visit WordPress Codex website to get more information’s about what custom queries are.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>