Home / Admin / Optimize Search Results
Duplicate Snippet

Embed Snippet on Your Site

Optimize Search Results

The default search includes title, excerpt and content of all both pages and posts. This snippet exclude pages and search post title and excerpt only, for the frontend while keeping all default for admins.

Code Preview
php
<?php
// 1. Exclude pages from search results
function exclude_pages_from_search($query) {
    if (!is_admin() && $query->is_search && $query->is_main_query()) {
        $query->set('post_type', 'post');
    }
    return $query;
}
add_action('pre_get_posts', 'exclude_pages_from_search');
// 2. Search only titles and excerpts (exclude post content)
function search_title_excerpt_only($search, $wp_query) {
    global $wpdb;
    if (empty($search)) {
        return $search;
    }
    
    // Get the search terms
    $terms = esc_sql($wp_query->query_vars['s']);
    
    // Build a new search clause that only checks title and excerpt
    // This replaces the default search which includes post_content
    $search = " AND ((" . $wpdb->posts . ".post_title LIKE '%{$terms}%') 
    OR (" . $wpdb->posts . ".post_excerpt LIKE '%{$terms}%'))";
    
    return $search;
}
add_filter('posts_search', 'search_title_excerpt_only', 10, 2);   

Comments

Add a Comment