WP_Query class is an exceptionally powerful tool in WordPress. As you may know, every WordPress site contains a database that stores many posts (of many post types) that make up the bulk of that site’s content, and
WP_Query is the best way to fetch or retrieve a given selection of those posts for processing. So your theme files use it on regular basis, and a lot of plugins on your WordPress site will it.
The use and power of
WP_Query will make more sense as we get into the details, so let’s get started!
WP_Query and Object-Oriented PHP
WP_Query is a PHP class that has certain properties. When you say, in PHP,
new WP_Query() you create an object (or instance) of that class.
If object-oriented PHP is a new concept, you may want to read our introduction to the topic. If you’ve read it, or already understand the basics of object-oriented PHP, let’s apply those concepts to
WP_Query Object You Want
When you make a new
WP_Queryobject, you create a query that will pull from the WordPress database all the posts you request.
When you make a new
WP_Query object, you create a database query that will pull from the WordPress database all the WordPress posts you request.
So one of the first things you need to understand about
WP_Query is that by default, when you just say
new WP_Query, you don’t get much use from it. Rather, the way you create your object — the specific query you run — is how you harness the power of
The “constructor” or initializing method of
WP_Query takes just one parameter,
$args. This is common in WordPress — you just pass an array or string of
$args that contains a rich specification of what you want back. The depth of what’s possibly to put into your
$args are well beyond what would be valuable to share here, but we’ll cover the basic points. When you need to make a specific query for a specific purpose, I recommend you just consult the Codex.
$args parameter accepts both arrays and strings, and the syntax is slightly different between them. I recommend you mostly build your
$args as arrays, because they can take you way further and with less mental weight than strings will.
A WP_Query Example: Get All Link Posts I Wrote Recently
The Codex recommends that you can get all posts from a specific user with this syntax:
$query = new WP_Query( 'author_name=rami' );
As I mentioned, though, I’ll be using arrays, because it’s much easier to keep track of everything with a well-formatted
This article was written by David Hayes and originally published on WPShout.