• I need to run a query that sorts by three things, being two custom fields and the post title. I have gotten it to sort by ONE custom field and the title using the code below, but I can’t figure out for the life of me how to incorporate the second. It seems like the solution ought to relate somehow to the example of how to use multiple meta fields given here: WP_Query#Custom_Field_Parameters, but were I to set both in the query, I don’t see how I could differentiate them when it comes time to deal with the orderby section of things.

    function foo_modify_query_order( $query ) {
        if ( $query->is_home() && $query->is_main_query() ) {
            $query->set( 'meta_key', 'ratings_average');
    		$query->set( 'orderby', array( 'meta_value_num' => 'DESC', 'title' => 'ASC' ));
            $query->set( 'order', '' );
        }
    }
    add_action( 'pre_get_posts', 'foo_modify_query_order' );

    Any advice on this would be much appreciated….

Viewing 1 replies (of 1 total)
  • I am not sure that this can be done using pre_get_posts. It will require a JOIN to join a second instance of the wp-postmeta table to retrieve the second meta_value. This can be done using the filters provided for queries.

    Here is an example that shows a similar situation where the filters were used to assign a value based on the presence or absence of a meta_key so that all posts with the key could be sorted before all those without it. The example is not exactly like your situation, but it may give you enough information to be able to solve your problem.

Viewing 1 replies (of 1 total)
  • The topic ‘How to add a second custom field to a query for sorting’ is closed to new replies.