What is WP_Query?

Posted OnNov 20, 2013     CategoryDevelopment     CommentsNo comment

WP_Query is a PHP class included with WordPress, and WP_Query’s job is to handle the request for a post or page in fact, it’s more or less what makes WordPress work, and runs every time a page is loaded. It also stores a great deal of information that you can pull out to display.

In addition to this, you can use it to create highly customized loops to retrieve very specific data.

Here’s an example of a standard WordPress Loop, created with WP_Query, that retrieves posts from a category with the ID of 4.


   $args = array('cat' => 4);
   $category_posts = new WP_Query($args);

   if($category_posts->have_posts()) : 
      while($category_posts->have_posts()) : 

         <h1><?php the_title() ?></h1>
         <div class='post-content'><?php the_content() ?></div>      

      <p class="error">Oops, there are no posts.</p>


Leave a Reply

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

Send this to friend