Limit WP Search to only Post Title

cmsexpertss
cmsexpertss
18 May 2022

By default WordPress search query looks for the searched text in Post Title and Post Content as well. But that makes the search very robust and doesn’t feel a useful search. So here is the code if you want the WordPress default search query to look only in Post Title.

<?php
/**
 * Search SQL filter for matching against post title only.
 * @param   string      $search
 * @param   WP_Query    $wp_query
 */
function code_dplugins_search_by_title( $search, $wp_query ) {
    if ( ! empty( $search ) && ! empty( $wp_query->query_vars['search_terms'] ) ) {
        global $wpdb;

        $q = $wp_query->query_vars;
        $n = ! empty( $q['exact'] ) ? '' : '%';

        $search = array();

        foreach ( ( array ) $q['search_terms'] as $term )
            $search[] = $wpdb->prepare( "$wpdb->posts.post_title LIKE %s", $n . $wpdb->esc_like( $term ) . $n );

        if ( ! is_user_logged_in() )
            $search[] = "$wpdb->posts.post_password = ''";

        $search = ' AND ' . implode( ' AND ', $search );
    }

    return $search;
}

add_filter( 'posts_search', 'code_dplugins_search_by_title', 10, 2 );
?>

Was this article helpful?

Tags

Categories

Never miss new post again

Subscribe and get list of new posts in your inbox

Click to Copy