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!

2 Answers
2

Never forget that there’re actually two filters

// Add additional query args that are allowed by the API by default
pre_get_posts
// Modify the query herself
posts_clauses
// Inspect the resulting string - test this one in for e.g. phpMyAdmin
posts_request

So everything you can achieve using the pre_get_posts filter should be done there. The rest should be modified using the posts_clauses (or one of the more specific filters before).

// Modify the original query parts
function wpse70214_pre_get_posts( $query )
{
    var_dump( $query );
    return $query;
}
add_filter( 'pre_get_posts', 'wpse70214_pre_get_posts' );

// Modify the resulting query string parts
function wpse70214_posts_clauses( $pieces )
{
    var_dump( $pieces );
    return $pieces;
}
add_filter( 'posts_clauses', 'wpse70214_posts_clauses' );

// Then check the result
function wpse70214_posts_request( $query_string )
{
    var_dump( $query_string );
    return $query_string;
}
add_action( 'posts_request', 'wpse70214_posts_request' );

Leave a Reply

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