Sorting posts by meta_value when they’re saved as an ACF serialized array
What I searched for
"acf" sort by meta_value serialized
Why I searched for it
I’m using Advanced Custom Fields to let a site manager pick one or more US states to associate with each Chapter (a custom post type).
I want to display the Chapters in a list sorted by the state in alphabetical order; however, because of the feature that lets people select more than one, the states are saved as a serialized array in the wp_postmeta table like so:
a:1:{i:0;s:9:"Louisiana";}
a:2:{i:0;s:6:"Oregon";i:1;s:10:"Washington";}
This means they essentially get sorted by the number of states and length of the first value.
What I learned
Via this forum post and answer, I learned that ACF has a handy acf/save_post action hook that fires (not surprisingly) when the post saves and provides ready access to the ACF fields.
Using that action, I checked if the post had the “state” field, and if it did, I looped through and built a plain-text, lowercase version (including multiple states if they were selected, in the order they were arranged within the editor). Then I saved it as a “shadow” meta-data record that can be used in conjunction with the WP_Query’s orderby parameter.