I have been working with custom post types in WordPress for several years now, but never really found a suitable solution for ordering any of the default or custom columns properly. By default WP will order all custom post types by date, which sucks if you want them to sort by menu order, their title, or some other custom column you’ve created.
Every tutorial I came across (not to say every single one out there is wrong) either didn’t work for me, was outdated, etc. So, here’s how I just started doing it.
My custom post type is for floor plans for houses. They include bedrooms, bathrooms, dens, etc. The meta data is both text and numbers.
The first things I have done are add the
pre_get_posts action with my custom function, then test to make sure that this is the admin screen and that the custom post type is being worked on.
After that, I found that
$query->get( 'orderby' ); will always return a result, and I wanted to test for an empty value to be able to set my own. Once an
orderby is set, it will be in the
query array under the
query object. With that somewhat explained, this is why I check to see if
$query->query[ 'orderby' ] is empty or not, then set a variable accordingly.
The default sorting direction is
desc, so I use the same method to test to see if it is set with
$query->query[ 'order' ], defaulting it to
asc if it is not set.
The big switch! Actually, this is all you really need to take a look at:
When sorting by a custom column, you must set a
meta_key to sort by. You then set
meta_value if it is a text sort and
meta_value_num if it is a numerical sort. This can be seen with
My default is
menu_order due to I am using a plugin named Post Types Order to allow the users to drag and drop their order. If you do this, you will need to include the case for
title as I have done. Or you could just make your default
I actually wouldn’t have gotten this far without Stephen Harris’ post Make Your Custom Column Sortable.