How To Search Post Title & Meta Value In WordPress

Trying to search the post title and meta value in WordPress at the same time inside your query? All you may need is to implement some functions.

Creating and using a search "title and meta value" function

Creating The Title & Meta Search Function

To search both title and meta values together in your WordPress query, you need to add a function to your WordPress theme’s functions.php file.

  1. Navigate to Appearance > Editor > Theme Functions from your WordPress Dashboard;
  2. Add the below PHP function to this file and press Update File.
function title_filter( $where, $wp_query ){
 global $wpdb;
 if( $search_term = $wp_query->get( 'title_filter' ) ) :
 $search_term = $wpdb->esc_like( $search_term );
 $search_term = ' \'%' . $search_term . '%\'';
 $title_filter_relation = ( strtoupper( $wp_query->get( 'title_filter_relation' ) ) == 'OR' ? 'OR' : 'AND' );
 $where .= ' '.$title_filter_relation.' ' . $wpdb->posts . '.post_title LIKE ' . $search_term;
 endif;
 return $where;
}

Using The Title & Meta Search Function

  1. Locate the file you need the search function implemented on;
  2. Add the code below to your file;
  3. Adjust the code example variables (searching variable, post type and meta key);
  4. When using the current $_GET superglobal, your search should be https://example.com?example_search=test
add_filter( 'posts_where', 'title_filter', 10, 2 );
$searching = $_GET['example_search'] //Change from $_GET to any absolute variable if necessary
$map_posts = new WP_Query(
 array(
 'post_type' => 'example_post_type',
 'title_filter' => $searching,
 'title_filter_relation' => 'OR',
 'meta_query' => array(
 'relation' => 'OR',
 array(
 'key' => 'example_meta_field',
 'value' => $searching,
 'compare' => 'LIKE'
 )
 ) )
);
remove_filter( 'posts_where', 'title_filter', 10, 2 );