Restricting WordPress Search to Titles Only

WordPress comes with a built-in search functionality which search both the post title as well as the post content and display the results. However you can override this feature and limit the WordPress search to post titles only.

Quick Tip : How to Change Author URL Base in WordPress

To do this, you need to copy the following code snippet and paste it inside your functions.php file located within your theme directory.

//Search Only Title
function ccw_search_by_title_only( $search, &$wp_query )
{
    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( 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', 'ccw_search_by_title_only', 500, 2 );

 

0 Comments

Leave a Comment.