WP_Query is a class defined in
wp-includes/class-wp-query.php that deals with the intricacies of a post’s (or page’s) request to a WordPress blog. The
wp-blog-header.php(or the WP class in Version 2.0) gives the $wp_query object information defining the current request, and then $wp_query determines what type of query it’s dealing with (possibly a category archive, dated archive, feed, or search), and fetches the requested posts. It retains a lot of information on the request, which can be pulled at a later date.
Interacting with WP_Query
Most of the time you can find the information you want without actually dealing with the class internals and global variables. There are a whole bunch of functions that you can call from anywhere that will enable you to get the information you need.
There are two main scenarios you might want to use WP_Query in. The first is to find out what type of request WordPress is currently dealing with. The $is_* properties are designed to hold this information: use the Conditional Tags to interact here. This is the more common scenario to plugin writers (the second normally applies to theme writers).
The second is during The Loop. WP_Query provides numerous functions for common tasks within The Loop. To begin with, have_posts(), which calls $wp_query->have_posts(), is called to see if there are any posts to show. If there are, a whileloop is begun, using have_posts() as the condition. This will iterate around as long as there are posts to show. In each iteration, the_post(), which calls $wp_query->the_post() is called, setting up internal variables within $wp_query and the global $post variable (which the Template Tags rely on), as above. These are the functions you should use when writing a theme file that needs a loop. See also The Loop and The Loop in Action for more information.