Using WordPress for Web Application Development: Features: Custom Queries with WP_Query

We've been looking at how WordPress can be used as a foundation for application development, but one of the things that we've yet to cover that most modern frameworks offer is how to query the database to retrieve results for any given view.

Specifically, we haven't talked about how to get information out of the database and insert it into our pages.

If you're familiar with other frameworks, then you're likely familiar with an object-relational mapping system (an ORM).

For those who aren't familiar with an ORM, essentially, it's a piece of software that sits in between the application and the database, and allows us to retrieve rows and columns as objects, treat them as such, and then serialize their changes back to the database.

It's really cool stuff. However, WordPress does not offer that flexibility.

Instead, there are a set of APIs that it offers that allow us to make changes to the database. There are a number of APIs that are available for us to use, each of which we'll be exploring over this final set of articles.

First, we're going to take a look at WP_Query. Then, we'll take a look at WP_User_Query, followed by the $wpdb object that's available as a global in WordPress.

But more on that later. Now, on to WP_Query.


Querying the WordPress Database

Before we actually get into talking about querying the WordPress database, I think it's critical to outline exactly what this means, why it's important, and what it entails.

If nothing else, this is meant to level-set expectations for readers regardless of your level of experience.

1. What Does This Mean?

Querying the WordPress database represents exactly what you would expect: retrieving information from the database on which WordPress runs.

There's nothing terribly complicated about that. However, there are several different ways to do it, and it's important to know how to do it and what to avoid.

Generally speaking, there are three APIs that are available and recommended for us to use, and a few that are available, but are not recommended for use.

In this series of articles, we're going to cover all of that.

2. Why Is This Important?

If nothing else, this is important so that we understand the proper ways to retrieve and store information to the database in the safest, most secure ways possible.

Remember: in programming, just because something works doesn't mean that it's the best way to do it.

To that end, we're going to take a look at the recommended ways that WordPress provides for retrieving and saving data directly from and to the database.

After all, we want to make sure that we're not only building robust applications, but secure and efficient applications as well.

3. What Does This Entail?

As with most things, it entails learning an API. At least, that's the case for two of the query types.

For the final article, it requires that you know, or have a willingness to learn, SQL (as WordPress does allow you to write raw queries against the database). But more on that later.

For now, we'll simply be focusing on the APIs, the available parameters, and how/when to use them in our work.


Introducing WP_Query

Although you can read all about WP_Query in the WordPress Codex, I think it's worth distilling some of the finer points here in this article, especially if you're new to WordPress, or are seriously considering writing applications using WordPress.

The Codex defines WP_Query as the following:

WP_Query is a class … that deals with the intricacies of a posts (or pages) request to a WordPress blog. The wp-blog-header.php … 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.

Incredibly technical, right?

Here's how to think of it from a consumer's perspective:

  • WP_Query retrieves information about posts, pages, other custom post types, and archived data, and makes the requested information about that data available.

From a development perspective, think of it like this:

  • WP_Query is a way to retrieve information about post types and archived data as well as their associated meta data, and more. The information that's retrieved can then be read, manipulated, saved, and/or displayed in template files.

In short, WP_Query provides a standard way for us to query the database specifically around posts, pages, custom post types, and their associated meta data so that we can more easily work with the information WordPress stores.

Note: If you're looking for information on managing users or writing custom SQL queries, then wait until the next set of articles as we'll cover that information in more detail at that time.

How To Use WP_Query

Okay, so we've covered what WP_Query is, why it's beneficial, and how it should be used, but that only goes so far.

At this point, it's time to take a look at what parameters can be passed to WP_Query and some practical examples of how to use it.

First, WP_Query can take arguments for: Authors, Categories, Tags, Taxonomies, Generic Search Queries, Posts, Pages, Custom Post Types, Status, Pagination, Order of Record, Dates, Custom Fields, Permissions, caching, and Return Fields.

In short, just about anything related to post types, their categories tags, and their meta data can be retrieved using WP_Query.

A Word About The Loop

If you've looked at any WordPress theme code, or worked with WordPress in any capacity prior to reading this article, then it's very likely you've seen code like this:

And, in WordPress, this is what's known as The Loop.

In short, The Loop is where everything happens as it relates to displaying information retrieved from a query.

To that end, if you're writing a query using WP_Query, then you're likely going to be using this very same structure for your own work.

But we'll see more about that in a moment.

Practical Examples

Getting started with WP_Query is easy. For example, let's say that we want to set up a template that displays all of the posts for a single author.

To do that, we can use the author's ID. So let's say we want to retrieve all of the posts, pages, and content written by the author with the ID of '1.'

And then we want to iterate through it:

Easy enough, right?

But let's make it a little more complicated. Let's say that we only want to retrieve the posts from that author that fall under the 'Photography' custom post type and that were published in 2013.

To do that, we'd pass this information:

And then iterate through the query like this:

But it can get a bit more complex depending on the information that we have on hand at any given point during the application's life cycle.

For example, let's say that we want to programmatically create a custom post type with a specific title and slug, but only if one doesn't already exist.

There are three steps to doing this:

  1. Pass the necessary arguments to the class
  2. Run through The Loop looking for any posts that may exist
  3. If the post doesn't exist, then create it

Here's how to do that:

As you can tell, you can make some really powerful queries, and do some really clever work with WordPress and WP_Query if you know how to handle the parameters correctly.

Now, in the code above, when we're looking to find if the post already exists in the trash, there are more optimal ways to write a query to check for that; however, the code above is meant to demonstrate more of an example of how to do it using WP_Query than anything else.

As we get further into this topic of writing queries, we'll see other ways to more quickly retrieve information (such as using raw SQL for SELECT statements and DELETE or UPDATE statements).

To that end, I highly recommend familiarizing yourself with the all of the parameters that it accepts. Though there are a lot of options (which is a good thing, in my opinion), there's a relatively standard way of passing them such that many of them perform the same way as others.

That is to say that once you learn a few of them, then it's easy to pick up the rest.

On top of that, if you're really into understanding the queries a bit more, I recommend taking a look at how the parameters correspond to the data in the underlying database.

When To Use WP_Query

Of course, this raises the question of when should you be using WP_Query.

After all, WordPress has its own template hierarchy so if you're working with a file that fits within said hierarchy, it's automatically going to be using a query related to that template type.

But writing applications, or even advanced WordPress themes, will have you creating templates that do not fit in the hierarchy, and thus need their own set of queries.

That's one way in which you'll need to use WP_Query.

Secondly, if you're looking to pull back a custom set of information - be it one piece, or multiple pieces - for a given post, page, custom post type, category, taxonomy, or so on, then WP_Query is arguably your best option.

A Word About Resetting The Query

There's one big gotcha to using WP_Query that's key to rounding out your understanding of the API and that is wp_reset_postdata().

Just as the Codex describes:

Use this function to restore the global $post variable of the main query loop after a secondary query loop using new WP_Query. It restores the $post variable to the current post in the main query.

Because of how WordPress maintains information using global variables, it's crucial that once you've crafted, executed, and processed your own WP_Query, then you need to call this particular function to restore information to the state that it was in prior to when you ran your own query.

This is so that WordPress continue looping through information as needed in the template hierarchy, and so that data isn't mangled or lost when rendering content later in a page or on another page.


Next Up, WP_User_Query

If WP_Query is so crucial to crafting efficient, secure queries for post types and their related attributes, how do we do the same for users?

After all, we've already established that, out of the box, WordPress offers fantastic facilities for account management, but we've not actually discussed the ways that we can manage users through querying the database.

In the next article, we'll take a look at exactly that. And if you're familiar with WP_Query - which you should be after reading this article - then you'll find the next article very easy to follow.

Tags:

Comments

Related Articles