multiple orderby in pre_get_posts action

I used to be able to sort query results by 2 criteria (“sort results first by status=unsold ASC then by date DESC) like this:

add_action( 'pre_get_posts', 'my_get_posts' );

function my_get_posts( $query )
{
    if (is_admin()){
        return;
    }

   if (is_post_type_archive('objet')){

            // Stock: sort by unsold first, then by date
            $query->set('meta_key', 'wpcf-object-sold-status' );
            $query->set('orderby', 'meta_value date');
            $query->set('order', 'ASC DESC' );
        }
    return $query;
}

But now, it does not change the result order anymore. I have no idea why it stopped functioning. Maybe the update from WordPress 3 to 4?

1
1

As Milo said :

$query->set('meta_key', 'wpcf-object-sold-status' );
$query->set('orderby', array('meta_value' => 'ASC', 'date' => 'DESC'));
// $query->set('order', 'ASC DESC' ); // not needed

Relevant link: https://make.wordpress.org/core/2014/08/29/a-more-powerful-order-by-in-wordpress-4-0/

Leave a Comment