This often happens when doing a search: you don’t understand why one post comes up rather than another. The best criterion of relevance remains the title for a lot of webmasters. I myself had the problem when back-office searches in an ACF field gave me anything and everything.

posts_search hook

Copy paste the following code into your theme’s functions.php;

function search_with_titles_only( $search, $wp_query )
{
    global $wpdb;
 
    if ( empty( $search ) )
        return $search; 
 
    $q = $wp_query->query_vars;    
    $n = ! empty( $q['exact'] ) ? '' : '%';
 
    $search =
    $searchand = '';
 
    foreach ( (array) $q['search_terms'] as $term ) {
        $term = esc_sql( like_escape( $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;
}
add_filter( 'posts_search', 'search_with_titles_only', 500, 2 );
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Commentaires
Inline Feedbacks
View all comments