There is a plugin that I am trying to adapt for my meta_tags for use with WordPress. It is called Categories by Title by http://www.mikesmullin.com.
What I am trying to achieve is a nested sort. I have three meta_keys. A selection-no, release-month, and release-year. I would like to sort posts within their category by release-year (asc), release-month (asc), then selection-no (asc). For example: 1955 10 selection-no-1, 1956 10 selection-no-2, 1956 10 selection-no-5, and so on.
I have modified the code, however, it only sorts by the last meta_key listed, by release-year.
Here is the code.
add_action('pre_get_posts','sort_categories_by_title');
function sort_categories_by_title($x) {
if(is_category()) {
$x->query_vars['orderby'] = 'meta_value';
$x->query_vars['meta_key'] = 'selection-no';
$x->query_vars['meta_key'] = 'release-month';
$x->query_vars['meta_key'] = 'release-year';
$x->query_vars['order'] = 'asc';
}
}
Any help would be greatly appreciated. Thank you.
Have a look at usort. You supply a comparison function which can look inside each item and choose what to order by.
In your example, every time you do $x->query_vars['meta_key']
you overwrite the previous value, so you're only adding the last meta_key as a selection option.
On top of that WordPress only supports pulling by a single meta_key/meta_value comparison. To get the more complex comparison that you're after you should be filtering on posts_where_paged
to add in more comparisons and posts_orderby
to construct the order by clause that you need. You'll need a basic knowledge of raw SQL query writing to accomplish this.
You might consider restructuring your data as well and putting the release-date in to a real date format and using typecasting to take the string format of the meta_value and cast it as a date field to then do proper date based sorting operations on it.