Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I would like to use a search form to search words but limit to ONLY search post titles and a custom field (in my case called "cities"). How can I do it?

Thanks.

share|improve this question
    
So the search is only for cities (e.g. London)? –  birgire Apr 28 '13 at 19:38
    
The search can be: london, madrid, roma –  Mike May 3 '13 at 19:24
    
Did you try the code below? –  birgire May 4 '13 at 14:05
add comment

1 Answer

Here is one idea using the posts_clauses filter:

function search_posts_clauses($clauses, $query){
    if(!is_admin() && $query->is_main_query() && $query->is_search()){
        global $wpdb;

        // replace post_content with meta_key and meta_value:
        $searchterms = explode(" ",get_query_var("s"));
        foreach($searchterms as $searchterm){
             $from = sprintf("{$wpdb->posts}.post_content LIKE '%%%s%%'", $searchterm);
             $to = sprintf("{$wpdb->postmeta}.meta_key = 'cities' AND {$wpdb->postmeta}.meta_value = '%s' ", $searchterm);  
             $clauses["where"] = str_replace($from, $to, $clauses["where"]);
        }

        $clauses["join"] = "INNER JOIN {$wpdb->postmeta} ON ({$wpdb->posts}.ID = {$wpdb->postmeta}.post_id) ";
    }
    return $clauses;
}
add_filter( 'posts_clauses', 'search_posts_clauses', 10, 2 );

where we modify the where and join parts for the main search query.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.