Search using specific meta fields only (excluding post title and content)

I have a custom post type my_cpt with 9 custom meta fields like first_name, last_name, location, phone, email etc along with post title and post content. Now what I want is to search using first_name and last_name fields only.

See this sample post-

  • Post Title: New Player (post title field of WP editor)
  • Description: Lorem ipsum dolor sit (post content field of WP editor)
  • first_name: John (custom meta)
  • last_name: Doe (custom meta)
  • phone: 123466789 (custom meta)
  • email: [email protected] (custom meta)
  • location: LA (custom meta)

Now if someone searches for

  • Player, he gets no results.
  • Lorem, gets no results.
  • John, he founds this post
  • LA, gets nothing

Topic meta-query Wordpress

Category Web


You can use WP_Query for this:

$query = new WP_Query( array( 'post_type' => 'my_cpt' ) );

This will query only posts of the type my_cpt.

To search only for posts with a certain first or last name, you have to extend the query. For this you need to add the field meta_query:

$query = new WP_Query( array( 
                      'post_type' => 'my_cpt' ),
                      'meta_query' => array(
                         'relation' => 'OR', //defaults to AND
                          array(
                             'meta_key' => 'first_name',
                             'meta_value' => $search_string,
                             'compare' => 'LIKE'
                          ),
                          array(
                             'meta_key' => 'last_name',
                             'meta_value' => $search_string,
                             'compare' => 'LIKE'
                          )
                       ));

To use this query you probably gonna need a custom search form where you would change the search parameter from s to something like search_my_cpt.

After you did this you need to edit your search.php // this is where the results are displayed:

you need to add something like this:

if( isset($_GET['search_my_cpt'])) {
//your new query
//display your search results
}

I didnt test this code, but this should bring u very close to what u want to achieve

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.