Pushing a custom post type to the top of the search results

Since WP 3.7 there is a filter "posts_search_orderby" that allow to set the ordering for search.

To be sure that filter works as expected set "orderby" to "relevance".

add_action( 'pre_get_posts', function( $query ) {
  if ( $query->is_search() ) {
    $query->set( 'orderby', 'relevance' );
  }
} );

and then, assuming your profiles CPT slug is “”profiles”:

add_filter( 'posts_search_orderby', function( $search_orderby ) {
    global $wpdb;
    return "{$wpdb->posts}.post_type LIKE 'profiles' DESC, {$search_orderby}";
});

In this way as usually, will be shown all posts that have the searched keywords in post title or post content, but ordering in this way:

  1. posts with profiles CPT, no matter if searched keywords are in title or in content, ordered by descending date
  2. posts with searched keywords in title, no matter post type, ordered by descending date
  3. posts with searched keywords in content, no matter post type, ordered by descending date

Leave a Comment