WP Query orderby meta key natural sort?

No, not as a straight WP_Query. This is because of several factors, with the main one being that mySQL doesn’t natively have a natural sort for alphanumeric columns.

WordPress does support a “meta_value_num” for the orderby parameter, which causes it to cast the values to numeric to perform the sort, and this works when you’re putting wholly numeric data in the meta_value’s, but since you have a mixed set of text and numbers, you can’t use that.

You can add a filter to the posts_orderby and rewrite the orderby clause directly to make it whatever you like. If your data is always going to start with “FA”, then you could make your filter return something like this:

LENGTH(meta_value) ASC, meta_value ASC

That first sorts by the length, then by the value. So shorter items come first, giving you a semi-natural sort.

Leave a Comment