WordPress: WP_Query – An Introduction

By default, WordPress will run a query on each page that site displays, the nature of which will be identified by the kind of web page being viewed.

But sometimes we need to do things a bit differently, either in page’s main content or elsewhere on the page such as sidebar or footer. WordPress makes that possible with the WP_Query class.

What Is WP_Query?
WP_Query is a class which is provided in WordPress CMS. The fact that it’s a class means that by using it you can quickly access the variables, checks, and functions which have been written into that class in WordPress core, without having to be worried about writing all that code yourself. This makes your rule code effective and reliable.

If you want to understand exactly how WP_Query performs then you can see its code in the includes/query.php wordpress core file.

In exercise this will look something like the following:

Resetting Post Data
In the example above I’ve included wp_reset_postdata() after each query. This is essential because it resets the query back to the primary query being run on that page. For example, if you’re using WP_Query to run a query in the sidebar, using wp_reset_postdata() successfully informs WordPress that we’re still on whatever web page is being viewed and that it should perform with the default query for that page.

Why Use WP_Query Over Other Methods?
WP_Query isn’t the only method for creating a custom query. There are a few more:

  • pre_get_posts is a hook which modifies the primary query. You can use it with a conditional tag to check if a certain kind of page is being viewed (eg. home page) and then use it to change the query that’s run (for example to remove the first three posts, if you’re displaying them elsewhere on the page). It’s a very effective way of changing the main query and should be first stop if that’s what you want to do. However, you can’t use it to make an entirely new query.
  • get_posts() and get_pages() are very identical, with the main difference being obvious from their names. These template tags actually use the WP_Query class, so they are another way of doing the same, but add an additional phase because they call the WP_Query class instead of you doing it directly. You can only use them to query either posts or pages, while WP_Query itself is more powerful and allows you to query almost anything kept in your database.
  • query_posts() modifies the primary query but shouldn’t be used in plug-ins or themes. This is because it throws out the primary query and begins all over again, replacing the primary query with a new query. It is also prone to mistakes, particularly with pagination, and is ineffective and will affect your web page loading time. If you need to alter the primary query, use pre_get_posts instead, and if you want to create a completely new query, use WP_Query.

WP_Query

Leave a Reply

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