In this post I’ll give you an in-depth look into how WP_Query works – let’s get started!
This series on WP_Query, you’ll learn how to use WP_Query to query for posts, pages and custom post types. You can query for specific posts and pages or you can run a query to return posts of one or more post types.
Why We use WP_Query?
As you might have noticed in the preceding two paragraphs, I keep referring to the WP_Query object. That’s because when you use WP_Query you are using what is called object-oriented PHP. Most people, myself included don’t even realize this when they start using WP_Query.
Think of the WP_Query object as a specially built container for the posts you need and some helpful methods–functions inside that container–for working with them. For example, in a normal WordPress loop, we begin the loop like this:
<?php while ( have_posts() ) : the_post(); ?>
When using WP_Query we start our loop like this:
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
Because we want the posts from a specific WP_Query object, which in this case is stored in the variable $query.
If you haven’t used the WP_Query class before, you may be wondering why you should start. Here I’m going to focus on two aspects of this: why use WP_Query over other methods of writing custom queries, and scenarios where you might want to use WP_Query.
<?php $query = new WP_Query( array( 'post_type' => 'post', 'posts_per_page' => -1, 'post_status' => 'publish' ) ); if ( $query->have_posts() ) : ?> <?php while ( $query->have_posts() ) : $query->the_post(); ?> <div> <h2><?php the_title(); ?></h2> <?php the_content(); ?> </div> <?php endwhile; wp_reset_postdata(); ?> <!-- show pagination here --> <?php else : ?> <!-- show 404 error here --> <?php endif; ?>
You can see here post_status-
post_status (string / array) – use post status. Retrieves posts by Post Status. Default value is ‘publish’, but if the user is logged in, ‘private’ is added. Public custom statuses are also included by default. And if the query is run in an admin context (administration area or AJAX call), protected statuses are added too. By default protected statuses are ‘future’, ‘draft’ and ‘pending’-
‘publish’ – a published post or page.
‘pending’ – post is pending review.
‘draft’ – a post in draft status.
‘auto-draft’ – a newly created post, with no content.
‘future’ – a post to publish in the future.
‘private’ – not visible to users who are not logged in.
‘inherit’ – a revision. see get_children.
‘trash’ – post is in trashbin (available since Version 2.9).
‘any’ – retrieves any status except those from post statuses with ‘exclude_from_search’ set to true (i.e. trash and auto-draft).