Search in post title and custom fields

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.

Related posts

Leave a Reply

1 comment

  1. 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.