WordPress Queries – Ordering by ‘meta_value’ where the ‘meta_key’ is an Array

Given that most of my daily web work is building websites for Musicians, I developed a set of Custom Post Type code (I hesitate to call it plugin since it’s not packaged yet — on the to-do list!) to collect and display details about Artist Recordings. To try and keep database bloat down, I saved the numerous Custom Fields I used in a single key, as an array. This worked great until I realised that it would be advantageous to be able to display them ordered by Release Year; one of the fields in the array.

This has been on my mind for a while and I happened across a solution today. It turns out that WordPress will quite happily allow meta_key values which are arrays. It simply uses the 1st field in the array to sort by. Therefore, if you put the field you want to sort by first in the array, you can sort by that field. Feels a bit hackish, but it works!

One thought on “WordPress Queries – Ordering by ‘meta_value’ where the ‘meta_key’ is an Array”

  1. This post just saved me big time!! For me, I had to use meta_value_num for this to work. Not really sure of the difference based on the Codex descriptions, but like you said — it works (and doesn’t seem to break things)!

Leave a Reply

Your email address will not be published. Required fields are marked *