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

According to:
http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters

Default order is DESC and default orderby is date.

Read More

In a custom plugin, plugin is applying the following pre_get_posts filter:

function custom_search_filter($query) {

    //echo '<pre>'; var_dump($_GET); echo '</pre>'; die;
    //echo '<pre>'; var_dump($query); echo '</pre>'; die; 

    if ($query->is_search) {

        /* -------------------------------------------------- */

        $query->set('orderby', 'date');

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

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

                $query->set('order', 'DESC');

                //echo '<pre>'; var_dump($_GET); echo '</pre>'; die;

            } else {

                $query->set('order', 'ASC');

                //echo '<pre>'; var_dump($_GET); echo '</pre>'; die;

            }

        }

        /* -------------------------------------------------- */

    }

    return $query; 

}


add_filter('pre_get_posts', 'custom_search_filter', 999);

The GET URL sets order to ASC:

http://mysite.lh/?post_type%5B%5D=resources&custom-search-my-term=Add+New+Term&s=CustomSearch&order=ASC

And debugging the query I get:

SELECT SQL_CALC_FOUND_ROWS wp_posts.* FROM wp_posts WHERE 1=1 AND wp_posts.post_type = ‘resources’ AND (wp_posts.post_status = ‘publish’) ORDER BY wp_posts.menu_order, wp_posts.post_date DESC LIMIT 0, 10″

In SQL above, You can notice: ORDER BY … DESC

Theres a reason why order is not changing from DESC to ASC if actually $_GET[‘order’] == ‘ASC’?

Thanks in advance.

Related posts

Leave a Reply

1 comment

  1. 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);