Order WordPress search results by post type

Learn how to order WordPress’ search results by post type with a simple code snippet.

WordPress will order its search results by relevance, based upon how frequently the search term in question appears within the title and content fields of each post. In some circumstances, however, you may want to give preference to a certain post type over others and the code snippet below will help you order WordPress’ search results according to post type.

In the scenario below, let’s imagine you have a website full of Courses as well as a blog that sits within Posts. You want any Courses that are relevant to the user’s search query to appear above any blog posts, regardless of whether there are Posts that are more relevant.

WordPress’ posts_orderby hook allows us to customise the orderby statement of the main WordPress query. The callback function below ensures that this is only applied when the query in question is related to site search (is_search) and is not on the admin side (is_admin).

Next, we need to find a way to assign a numerical value to post types, ensuring that Courses has a lower value than Posts in our order by statement. MySQL’s CASE function provides a solution to this. CASE will run through a number of conditions that you specify and return a value when the first condition is met working much like an if, then, else statement.

The code snippet below creates a couple of conditions for both the ‘course’ and ‘post’ post types. If the post type of a result is ‘course’ then a value of 1 is assigned and if the post type is ‘post’ then the value is 2. In all other cases, the ELSE condition just applies the post_type field instead as well as the post_title field. Since we’re ordering search results in ascending order, Courses will appear high than Posts.

The code snippet can easily be extended to work with additional post types, placing them into the desired order within WordPress search results.

 * Order search results by post type to place Courses first

function order_search_by_posttype( $orderby, $wp_query ){

    global $wpdb;

    if( ! $wp_query->is_admin && $wp_query->is_search ) {

        $orderby =
            CASE WHEN {$wpdb->prefix}posts.post_type = 'course' THEN '1'
                 WHEN {$wpdb->prefix}posts.post_type = 'post' THEN '2' 
            ELSE {$wpdb->prefix}posts.post_type END ASC, 
            {$wpdb->prefix}posts.post_title ASC";


    return $orderby;

add_filter( 'posts_orderby', 'order_search_by_posttype', 10, 2 );

A lightweight, intuitive WordPress theme to enable flexible developement.

  • Lighting-fast installer
  • Intuitive SASS structure
  • Bloat-free

Build with Barebones