wordpresswp-admin

How to limit wp-admin to search only titles


I'm trying to limit the search in the WP admin area to just post titles.

I found code that offered a suggestion, however, this is not limiting the search to only the post/page titles:

add_filter( 'posts_search', 'wpse_45153_filter_search', null, 2 );
function wpse_45153_filter_search( $search, $a_wp_query ) {
    if ( !is_admin() ) return $search; // work only in the dashboard

$search = preg_replace( "# OR \(.*posts\.post_content LIKE \\'%.*%\\'\)#", "", $search );

return $search;
}

Solution

  • Try this instead:

    add_filter( 'posts_search', 'search_by_title_only', 10, 2 );
    function search_by_title_only( $search, $wp_query ) {
        if ( !is_admin() || empty( $search ) ){
            return $search;
        }
        global $wpdb;
        $q = $wp_query->query_vars;
        $x = ! 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 '{$x}{$term}{$x}')";
            $searchand = ' AND ';
        }
        if ( ! empty( $search ) ) {
            $search = " AND ({$search}) ";
        }
        return $search;
    }
    

    It essentially adds another clause (using 'AND') to the end of the query where the name must contain the search string provided.