Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make WordPress search only in post title

Tags:

wordpress

I have a new website and I want to modify WordPress Mystique theme 3.0 in order to search only in post title.

How can I do it?

like image 849
Rania York Avatar asked Feb 27 '12 16:02

Rania York


1 Answers

There are numbers of articles available in Google if you have searched before you posted.
WordPress search only in post title

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($wpdb->esc_like($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);

Add this code to your functions.php

like image 50
Rizwan Mumtaz Avatar answered Oct 30 '22 01:10

Rizwan Mumtaz