WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?


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

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

Your Answer


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.