Apply customized order to search results

Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInPrint this page

A default search returns the found objects for all site custom post types. This makes difficult a sort to be created, which will apply for the search result, as is require all objects to be displayed in the list, which for large sites means thousand of items.

There’s an easy approach for this, to include a post type argument in the search, form, this way the WordPress will query and search the objects only of specified post type, which can be a fraction of total items.

The first step is to create a sort list for the post type, unless already exists. The Archive selection will be used when applying the order on the search results. If a sort already exists, this step can be ignored.

A post_type argument should be inserted in the search form. Usually, the form can be found within one of the theme files, a search should fast reveal the exact place:

<input type="hidden" name="post_type" value="post" />

After above change, in most of the cases, after submiting the search the url becomes like this:


As default the sort list order is ignored and will not apply on front side for search queries to avoid confusions. This can be modified through a filter apto/ignore_search available through the plugin version and later.

The following code should be placed in a file on your site /wp-content/mu-plugins/

add_filter( 'apto/ignore_search', 'apto_ignore_search', 10, 3 );
function apto_ignore_search ( $status, $orderBy, $query )
        if  ( 
            ( isset ( $query->query_vars['post_type'] ) &&  is_string( $query->query_vars['post_type'] )    &&  ! empty  ( $query->query_vars['post_type'] )    &&  $query->query_vars['post_type'] !=  'any' )
            ( isset ( $query->query_vars['post_type'] ) &&  is_array( $query->query_vars['post_type'] )    &&  count( $query->query_vars['post_type'] ) == 1 )
            $status =   FALSE;

        return $status;