search

Limit search to post titles only

search post titlesI know that this is not something new on scene but anyway there snippet to limit search to the post titles only.

Yesterday client witch for I was working on a real estate template asked me: Is there a way to limit search to post titles only?

Here are the snippet that I’ve used to enable search for post titles only.

This search filter could be use various combinations to query any other custom post type. For example we could query custom post type “Portfolio” simply by replacing snippet with this code: $query->set(‘post_type’, ‘portfolio’);

Filter search to posts only

[php]
/**
* Snippet Name: Limit search to posts
* Snippet URL: http://wperror.com/limit-search-to-post-titles-only.html
*/
function SearchFilter($query) {
if ($query->is_search) {
$query->set(‘post_type’, ‘post’);
}
return $query;
}
add_filter(‘pre_get_posts’,’SearchFilter’);
[/php]

Filter search to titles only

[php]
/**
* Snippet Name: Limit search to titles only
* Snippet URL: http://wperror.com/limit-search-to-post-titles-only.html
*/
function __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’, ‘__search_by_title_only’, 500, 2 );
[/php]

As you can see, the first snippet is used to limit search function to the posts only, while the other search by title only.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>