How to alter query order direction using $query->set(‘order’, ‘ASC’); inside a pre_get_posts filter?

Yes, I got it:

function custom_search_orderby($orderby) {

    global $wpdb;

    if  ( is_search() ) {

        if ( isset($_GET['order']) ) {

            if ( $_GET['order'] == 'DESC' ) {

                $orderby = $wpdb->prefix . "posts.post_date DESC";

            } else {

                $orderby = $wpdb->prefix . "posts.post_date ASC";

            }

        }

    }

    return $orderby;

}

add_filter('posts_orderby', 'custom_search_orderby', 999);

Leave a Comment