Trying to search the post title and meta value in WordPress at the same time inside your wp_query? All you may need is to implement some functions.
1 answers
1
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.
- Navigate to Appearance > Editor > Theme Functions from your WordPress Dashboard;
- 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
- Locate the file you need the search function implemented on;
- Add the code below to your file;
- Adjust the code example variables (searching variable, post type and meta key);
- 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 );
— Support WizardAnswer 1