Blog

Configure WordPress Backend Search to Search Titles Only

WordPress

By default, the WordPress backend search searches for post titles and the post content. If you have a lot of pages, it can be hard to find the correct page when you want to link pages or insert pages to a menu.

If you want to change that, so that WordPress only searches for the post title (in the backend), you can use this code snippet:

if ( is_admin() ) {
    add_filter( 'posts_search', 'search_by_title_only', 500, 2 );
}

/**
* @param $search
* @param $wp_query
*
* @return string
*/
public function search_by_title_only( $search, $wp_query ) {
    // $wp_query was a reference
    global $wpdb;
    if ( empty( $search ) ) {
        return $search;
    } // skip processing - no search term in query
    $q = $wp_query->query_vars;
    $n = ! empty( $q['exact'] ) ? '' : '%';
    $search =
    $searchand = '';
    foreach ( (array) $q['search_terms'] as $term ) {
        $term      = esc_sql( $wpdb->esc_like( $term ) );
        $search    .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
        $searchand = ' AND ';
    }
    if ( ! empty( $search ) ) {
        $search = " AND ({$search}) ";
        if ( ! is_user_logged_in() ) {
            $search .= " AND ($wpdb->posts.post_password = '') ";
        }
    }
    return $search;
}