2

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.

3
  • So the search is only for cities (e.g. London)?
    – birgire
    Apr 28, 2013 at 19:38
  • The search can be: london, madrid, roma
    – Mike
    May 3, 2013 at 19:24
  • Did you try the code below?
    – birgire
    May 4, 2013 at 14:05

1 Answer 1

2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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