The WP_Query Function in WordPress

The WP_Query is a very powerful WordPress function used to make very specific WordPress loops based on a large number options.

The WP_Query function is placed before the loop. A nice aspect of this function is that all you have to do is place it before the loop and you don’t have to change anything about the loop itself.

Here are a few of the most common WP_Query options:

  • author – Filters loop by author id
  • author_name – Filters author by user_nicename
  • cat – Filters loop by category id
  • category_name – Filters loop by category slug
  • tag – Filters loop by tag slug
  • p – Filters loop by page or post id
  • name – Filters loop by post slug
  • pagename – Filters loop by page slug
  • page_id – Filters loop by page if
  • post_parent – Filters loop by id of parent page
  • post_type – Filters loop by post type, including custom post types
  • posts_per_page – Determines how many posts are looped through
  • offset – Determines how many posts to offset the loop by
  • order – Determines whether the posts display in ascending or descending order
  • orderby – Filters what factor the posts are sorted by. Default is date, but can be changed to things like title or author
  • year – Filters loop by posts in a given year
  • monthnum – Filters loop by a month numner. i.e. 1 = January
  • day – Filters loop by a specific day of the month

Usually all of the parameters are passed to the WP_Query function as an array.

Here is an example of using the WP_Query function to display the content for a specific page.

For a more complex example, we can look at how to display all of the posts published by a specific author in a custom post type called notes. We will also filter the loop so that it orders the posts by the title and only displays workshops published in the year 2012.