Adding a search criterium in my custom search box
-
Finally I got some more code to work on. I was trying to add a new search criterium to search my posts, the custom field meta key is “function_camere”, and I want to add another dropdown selector to choose a value for this new search criterium. I got a suggestion as follows on the link but this code broke my site, maybe have I to change something? https://wordpress.stackexchange.com/questions/421963/adding-another-search-field-in-a-custom-search-box/421976#421976
- This topic was modified 10 months, 1 week ago by sacconi.
The page I need help with: [log in to see the link]
-
Theme functions.php will work. AND is the default logic so you don’t really need the “relation” argument. But you still need the outer array containing several inner arrays, one for each taxonomy.
Something like that?
$args = array( 'post_type' => 'post', 'tax_query' => array( 'taxonomy' => 'function_camere', ),
I had reviewed your search box code that you recently linked to in another topic. The apartment’s bedroom (and person) count is saved as a meta value, not taxonomy term. So instead of setting “tax_query”, we set “meta_query”. This works to our advantage because meta_query args can use arithmetic operators. You’d set the “meta_query” arg like so:
$query->set('meta_query', array( array( 'key' => 'function_ospiti', 'value' => (int) $_GET['function_ospiti'], 'type' => 'numeric', 'compare' => '>=', ), array( 'key' => 'function_camere', 'value' => (int) $_GET['function_camere'], 'type' => 'numeric', 'compare' => '>=', ), ));
You should only do this for search box queries. Do the typical
(! is_admin() && $query->is_main_query())
check. Also confirm that $_GET has all the right elements that would confirm this is a search box request. You can use array_key_exists() for this.The taxonomy args (category and tipologia) should take care of themselves, you needn’t do anything special for them.
I just have to replace a part of what I already have or reorganize totally? Or mix both elements such as
foreach ($functionCamereValues as $value) { $query->set('meta_query', array( 'key' => 'function_camere', 'value' => (int) $_GET['function_camere'], 'type' => 'numeric', 'compare' => '>=', )); $functionCamereDropdown .= '<option value="' . esc_attr($value) . '" '. selected( $query, $value, false ) .' >' . esc_html($value) . '</option>'; } $functionCamereDropdown .= '</select>';
That’s part of your search box code, right? The “pre_get_posts” code does not belong there, it belongs in functions.php as its own code. Similar to “get_terms” filter, it indirectly affects the query being made.
Ok, I found something similar in my code, so followed the same track
function bedrooms_guests_search_query( $query ) { $custom_fields = array( // put all the meta fields you want to search for here "function_camere", "function_ospiti", ); $searchterm = $query->query_vars['s']; // we have to remove the "s" parameter from the query, because it will prevent the posts from being found $query->query_vars['s'] = ""; if ($searchterm != "") { $query->set('meta_query', array( array( 'key' => 'function_ospiti', 'value' => (int) $_GET['function_ospiti'], 'type' => 'numeric', 'compare' => '>=', ), array( 'key' => 'function_camere', 'value' => (int) $_GET['function_camere'], 'type' => 'numeric', 'compare' => '>=', ), )); } $query->set("meta_query", $meta_query); }; } add_filter( "pre_get_posts", "bedrooms_guests_search_query");
I also cant see where I should put
(! is_admin() && $query->is_main_query())
in order to avoid this search in the admin
Wrap the entire code in the conditional:
function bedrooms_guests_search_query( $query ) { if (! is_admin() && $query->is_main_query()) { //all code to alter the query goes here } }
I tryed https://pastebin.com/YHipqn43 but it has no effect on my search results
$searchterm = $query->query_vars['s'];
AFAIK your search box does not send an “s” query var, so $searchterm == ” (empty string). Then because ofif ($searchterm != "")
nothing else happens.Instead of checking “s” query var, maybe check “tipologia”? But will tipologia appear as a query var in any other request? If so, check for something that’s unique to your search box query. Check for all 4 fields if you have to. The meta fields will not appear as query vars, get those from
$_GET
.Or maybe verify
'Cerca' == $_GET['search']
if that does not appear in any other request. What is key is to be sure this is a search box query and not anything else.If I have well undestood this code is for making work 2 fields: n.of guests (funzione_ospiti) and n. of bedrooms (funzione_camere), but shouldnt I have two different functions, one for each meta key? All my custom search functions are in a separated file, here is it: https://pastebin.com/ee8VteN4
$searchterm = $query->query_vars['s'];
and
if ($searchterm != "")
are to be deleted?It’s possible to use two different callbacks to influence the same query, but it doesn’t really make any sense to do so. While there are two different aspects to modifying the query, they are for the same query. Two different callbacks gets particularly awkward when they both relate to the same “meta_query” query var. IMO all related code should be kept together in the same callback.
You need to check enough query vars to ensure you’re modifying the right query. If checking the funzione_camere value alone (for example) is enough, then that will work. If verifying requires checking more than one query var then you should do so.
For example, if all you needed to do to verify was to check for the tipologia query var, you could do:
$searchterm = $query->query_vars['tipologia'];
If so, then keepingif ( $searchterm != "")
is fine.However, when checking for meta data query vars like “funzione_camere”, they do not exist as query vars like taxonomies do. You’d need to check for these in
$_GET
. For these you might need to do something like:
if ( array_key_exists('funzione_camere', $_GET)
If you need to check more than one item to fully verify, use AND logic in the conditional. Perhaps:
if ( array_key_exists('funzione_camere', $_GET ) && $searchterm != "")
Ok, now I’m here: https://pastebin.com/kYmZjHaQ
Your add_filter() call should actually be add_action(). And it belongs outside of the bedrooms_guests_search_query() function, otherwise it’ll never be implemented.
There appears to be an extra closing
}
at the end of the code you posted.The meta values we’re querying for are integers. You don’t want to use LIKE comparison for integers. Even if it works, LIKE queries are very inefficient and slow. Always avoid if at all possible. For these values, you want to match posts with the the selected value or greater, so use
'>=
` for the “compare” arg.Other than those things, it looks pretty good. Nicely done! I’m not 100% sure there are no other issues. I’ve not tested it since I don’t have appropriate data in my DB. If for some reason it still doesn’t work, it’s likely something minor. You’ve addressed the major concerns.
This is kind of pedantic, but this is poor formatting:
if ( array_key_exists('funzione_camere', $_GET ) && $searchterm != "") if ( array_key_exists('funzione_ospiti', $_GET ) && $searchterm != "") $query->set("meta_query", $meta_query);
It’ll work as intended. But it’s recommended that we always demarcate conditionals with curly braces, even when not required. For example:
if ( array_key_exists('funzione_camere', $_GET ) && $searchterm != "") { if ( array_key_exists('funzione_ospiti', $_GET ) && $searchterm != "") { $query->set("meta_query", $meta_query); } }
This way it’s easier to grasp the intended logic. Also, the second
$searchterm != ""
is redundant, it’s not necessary even if it does work correctly. In fact, you don’t really need nested conditionals. You could do:if ( array_key_exists('funzione_camere', $_GET ) && $searchterm != "" && array_key_exists('funzione_ospiti', $_GET )) { $query->set("meta_query", $meta_query); }
I wonder if I can change the name “tipologia” in
$searchterm = $query->query_vars['tipologia'];
because “tipologia” is the name of my taxonomy, and this search criteria is already working without any more code, like the category (destination) search. If you check https://test.sacconicase.com/ you can see the first 2 selectors/search criteria are already working, I need only the last 2 selectors make work
“If it’s not broken, don’t fix it.” ??
Yes, leave it alone if there’s no need to alter the query to get posts by German translations. You only need to address the persons and bedrooms, which of course are integers and need no translation. The main reason to alter the meta query is to get posts with the form’s selection or greater.
- The topic ‘Adding a search criterium in my custom search box’ is closed to new replies.