Order by Meta Values

Huge props to Chris McCoy A.K.A “fris” (GitHub / Twitter) for schooling me in using add_filter for this.

I needed to add custom fields to the post type: Post within WordPress. That’s not problematic, in fact it’s rather quite easy. But, ordering Posts based on the assigned value of my custom field… that isn’t super straight forward.

This problem isn’t unique to what I was doing, many other people have written Plugins and Themes that already do this kind of stuff.

Most of the time you are working within WordPress, you’re going to be playing with Meta Values. Those things are everywhere. I’m not going to explain what they are here, but safe to say, you’ve used them before and you’ll continue on using them in WordPress.

Let’s look at some code:

That code produces SQL that looks like this:

The results of that query can look like this:


Leave a Reply