Ordering WordPress Posts by Custom Field

The default behavior for a WordPress post is to post by content publish date. On occasion, that order may need to be changed.

In a recent project, we had a list of upcoming events. We wanted 4 of these events to display on the front page of the site, in order of the event date (not necessarily the entry date).

We created an “Event” custom post type. It included a number of fields that were custom to that post type, including event date, ticket price, venue, ticket ordering link etc.

I just needed a way to sort that event_date field (stored as Y-m-d).

The Query

When WordPress goes to get the posts from your database, it runs through the “Query Posts” structure to get your content. It’s a pretty powerful function that allows the developer to pass a number of variables to the MySQL query. But sometimes… you just need a little more control.

In the case of our project, we needed to grab that custom field and use it to order the posts.

I was able to accomplish that by just passing my custom query to the $wpdb class

This post from the WordPress Codex helped me get that built