Show Pages Before Posts in Search Results
Lists matching pages first in search results, then blog posts, then other content, so key pages like pricing or contact are not buried under older posts.
Opens WPIDE on
Code
// Content types in the order they should appear in search results; anything else follows.
$wpide_search_type_order = array( 'page', 'post' );
add_filter( 'posts_orderby', function ( $orderby, $query ) use ( $wpide_search_type_order ) {
global $wpdb;
if ( is_admin() || ! $query->is_main_query() || ! $query->is_search() || ! $wpide_search_type_order ) {
return $orderby;
}
$case = "CASE {$wpdb->posts}.post_type";
foreach ( array_values( $wpide_search_type_order ) as $i => $type ) {
$case .= $wpdb->prepare( ' WHEN %s THEN %d', $type, $i );
}
$case .= ' ELSE ' . count( $wpide_search_type_order ) . ' END ASC';
// Within each type, WordPress's own relevance order is kept.
return '' !== trim( $orderby ) ? $case . ', ' . $orderby : $case;
}, 10, 2 );
Notes
Change the order list to rank other types, such as product or docs, at the top.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.