Reputation: 11
I want to filter my products with custom post meta_key
for "_city_name"
, as well as the keyword "s"
with AND
operation currently I'm doing in my functions.php
:
function my_modify_main_query( $query ) {
$meta_query_args = array(
'meta_query' => array(
array(
'key' => '_city_name',
'value' => 'new york',
'compare' => 'LIKE',
)
)
);
$query->set('meta_query', $meta_query_args);
}
add_filter( 'pre_get_posts', 'my_modify_main_query' );
It's working if I don't add keyword in the GET params "s"
.
But if I add keyword "s=beer&city=newyork"
, it stop working.
What I am doing wrong?
Upvotes: 1
Views: 4377
Reputation: 253867
First you need to always return something in a filter hooked function at the end:
return $query;
May be you should include $_GET['city']
for 'value'
this way: 'value' => $_GET['city'],
instead. But you will need to check before $_GET['city']
value.
So your code should be:
add_filter( 'pre_get_posts', 'my_modify_main_query' );
function my_modify_main_query( $query ) {
// Checking for "city" data
if( ! isset( $_GET['city'] ) ) return $query;
$meta_query_args = array(
'meta_query' => array(
array(
'key' => '_city_name',
'value' => sanitize_text_field( $_GET['city'] ),
'compare' => 'LIKE',
)
)
);
$query->set('meta_query', $meta_query_args);
return $query; ## <==== This was missing
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
I didn't test it, but it should work.
Upvotes: 2