I’m trying to include post meta into the wordpress admin panel search. I did a reseach and I found out that I can use the “pre_get_posts” filter to set the post meta into the query. So I wrote the following code
function custom_search_query( $query ) {
if( is_admin() && $query->is_search) {
$custom_fields = array(
// put all the meta fields you want to search for here
["key" => "property-ref-code", "compare" => "LIKE"],
["key" => "property-status", "compare" => "="],
["key" => "price", "compare" => "="],
["key" => "rent-price", "compare" => "="],
["key" => "bedrooms", "compare" => "="],
);
$meta_query = $query->get('meta_query');
if (empty($meta_query))
{
$meta_query = array();
}
$meta_query[] = array('relation' => 'OR');
foreach($custom_fields as $cf) {
$meta_query[] = array(
'key' => $cf["key"],
'value' => $query->query_vars['s'],
'compare' => $cf["compare"],
);
}
$query->set("meta_query", $meta_query);
}
}
add_filter( "pre_get_posts", "custom_search_query");
That code now not only is not returning anything but it also breaks the wordpress search. What I mean. If you disable this code you can search by post title and It will return some results if exists. Then if you enable the code and search by post title is not returning anything.
Basically I want to search for properties by price, reference code etc which are postmeta fields that I did. Can anyone help me to extends the wordpress search, when I search for a property to search and the given meta_keys
Thank you
The issue could be that
if (empty($meta_query_args))
always returns true as$meta_query_args
are not defined. So the actual meta_queries from the search are removed.