Referencing @Otto’s response to a question I also had about ordering by multiple fields, here is what he said:
Can’t do it with a naive WP_Query. Use the posts_orderby filter to add
your own ordering string.
function my_order($orderby) {
global $wpdb;
return "{$wpdb->posts.post_author} ASC, {$wpdb->posts.post_date} DESC";
}
add_filter( 'posts_orderby', 'my_order' );
$blah = new WP_Query(...);
remove_filter( 'posts_orderby', 'my_order' );
-Otto
This appears to be the way it would be done in a new call to WP_Query –> how would I go about this same thing in a pre_get_posts()
action with two meta fields, with a default sort to?:
function mouldings_sort($query) {
if ($query->is_main_query() && is_tax(array('wood_types','profile_categories','combination_categories'))) {
$query->set('meta_key', '_mouldings_dimensions_height');
$query->set('order', 'DESC');
$query->set('orderby','meta_value_num');
}
}
add_action('pre_get_posts','mouldings_sort');
I had previously tried simply adding in another meta field like so:
$query->set('meta_key', array('_mouldings_dimensions_height', '_mouldings_dimension_width'));
$query->set('orderby','meta_value_num');
with a default sortback of title
as so:
$query->set('orderby','meta_value_num title');
but it doesn’t look like meta_key
can accept arrays and my title
fallback goes back to Otto’s original response on the matter. Any help would be a greatly appreciated. Thanks!
Never forget that there’re actually two filters
So everything you can achieve using the
pre_get_posts
filter should be done there. The rest should be modified using theposts_clauses
(or one of the more specific filters before).Yes like Otto said you can’t have a secondary
ORDER BY
clause without a a customposts_orderby
filter. If you need to know what query your on a la “pre_get_posts” you can create a function that adds the orderby filter to posts_orderby and call it from pre_get_posts.