Shortcode for runnung a search-box
-
I created a shortcode and put the code in my functions.php, at the moment I have to define the function I want to display:
// function that runs when shortcode is called function wpb_demo_shortcode() { } // register shortcode add_shortcode('ricerca', 'wpb_demo_shortcode');
I’m trying to do a searchbox more or less like this:
I’d like to start with defining the form and the first selectors, which are concatenated one with other, which could be the point of start?
- This topic was modified 1 year, 2 months ago by James Huff. Reason: link moved to proper field
The page I need help with: [log in to see the link]
-
I’d like to erase the first selector out of the orange box: https://ibb.co/zrqf0cn
code
function wpb_demo_shortcode() { $categories = wp_dropdown_categories( array( 'show_count'=> 1, 'hierarchical'=> 1, 'show_option_all'=>'Tutte le destinazioni', 'echo'=> false, )); $taxonomy = wp_dropdown_categories( array( 'hierarchical'=> false, 'name'=>'tipologie', 'taxonomy' => 'tipologia', 'show_option_all'=>'Tipologia' )); $output = '<form class="sacconi_form" method:"get" action="' . home_url( '/' ) . '">'. $categories . $taxonomy .'<br></br>'.'<input type="submit" name="sacconi_search" value="Cerca">'. '</form>'; return $output; } // register shortcode add_shortcode('ricerca', 'wpb_demo_shortcode');
and creating a search query that connects the 2 selectors
- This reply was modified 1 year, 1 month ago by sacconi.
For the “tipologia” taxonomy, for that to work as an URL query string, its dropdown also needs a
'value_field'=>'slug',
arg added. Without it the query string would use the selected term’s ID, which will not work with'name'=>'tipologie',
. With the selection’s slug passed instead, I believe the query will work the way you want.The category dropdown with name “cat” is fine as it is with ID value fields.
I think you need to change the name of the submit field. I tried the form on your test site and I think it’s causing the request to go where we don’t want it to go. The submit name should not be anything meaningful to WP.
Exactly what do you want to remove? The entire category dropdown? The first option ‘Tutte le destinazioni’?
This is what I want to delete (red cross): https://ibb.co/DgyxhHY
I added
'value_field'=>'slug',
but I still cant have a combined search of the 2 selectors together. I changed the name of the submit into “search”:function wpb_demo_shortcode() { $categories = wp_dropdown_categories( array( 'show_count'=> 1, 'hierarchical'=> 1, 'show_option_all'=>'Tutte le destinazioni', 'echo'=> false, )); $taxonomy = wp_dropdown_categories( array( 'hierarchical'=> false, 'name'=>'tipologie', 'taxonomy' => 'tipologia', 'show_option_all'=>'Tipologia', 'value_field'=>'slug' )); $output = '<form class="sacconi_form" method:"get" action="' . home_url( '/' ) . '">'. $categories . $taxonomy .'<br></br>'.'<input type="submit" name="search" value="Cerca">'. '</form>'; return $output; }
Oh that one. Add
'echo'=> false,
arg to the related taxonomy dropdown call. We never echo out anything from a shortcode handler.Regarding the submit name behavior, I misunderstood what’s going on. The ?cat=287 query string from the category dropdown causes a redirect to the “pretty” permalink version of the URL. That should be OK. The ?tipologie=apartmento query string tacked on to it should still give you the results you want. (posts in category ID 267 AND having apartmento tipologie [or whatever category and tipologie] assigned as well)
If that’s not happening, some other code might be corrupting the usual query. Do you have any active custom “pre_get_posts” action hooks? They may need modification to allow the proper query to happen. You also might want to check the actual SQL using the Query Monitor plugin. It should have a clause within it similar to
AND ( wp_term_relationships.term_taxonomy_id IN (287) AND tt1.term_taxonomy_id IN (321) )
(the numbers could vary in number and value, but there should be two different taxonomy_id requirements)
I have 1 function using
add_filter( “pre_get_posts”, “custom_search_query”);and another using
add_filter(‘pre_get_posts’, ‘search_by_post_id’);
I have also a custom search box
function custom_search_form( $form ) { $form = '<form role="search" method="get" id="searchform" class="searchform" action="' . home_url( '/' ) . '" > <div class="custom-form"><label class="screen-reader-text" for="s">' . __( 'Search:' ) . '</label> <input type="text" placeholder="ricerca per codice" value="' . get_search_query() . '" name="s" id="s" /> <input type="submit" id="searchsubmit" value="'. esc_attr__( 'Search' ) .'" /> </div> </form>'; return $form; } add_filter( 'get_search_form', 'custom_search_form', 40 );
I use it to search by ID code, and (this is for my internal use) by apartment name
when I select a category and then a taxonomy term and push the action button, the taxonomy selected term desappears, it doesnt stay in the selector
But the plugin “search and filter” works perfecty…
The custom search box is related to search_by_post_id()? Does search_by_post_id() have a conditional to ensure it’s only acting on requests from the custom searchbox? Such as checking if the “s” query var exists, is an integer, or something similar?
Same for custom_search_query(). Is something checked to ensure it’s only acting on the intended requests and not any others?
Something is not checking well enough otherwise a combined “cat” and “tipologia” request (from the field names) should work the way you want.
If you’re not sure, please share the source code for those pre_get_posts callback functions and I’ll have a look.
These are my 3 functions concerning “search”.
//CERCA PER ID- aggiornato function search_by_post_id($query) { if($query->is_search) { if(is_numeric($query->query_vars['s'])) { $query->set('post_type', 'any'); $query->set('post__in', array((int)$query->query_vars['s'])); $query->set('s', ''); } } return $query; } add_filter('pre_get_posts', 'search_by_post_id'); //RICERCA PER NOME su stackexchange function custom_search_query( $query ) { $custom_fields = array( // put all the meta fields you want to search for here "function_name", ); $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 != "") { $meta_query = array('relation' => 'OR'); foreach($custom_fields as $cf) { array_push($meta_query, array( 'key' => $cf, 'value' => $searchterm, 'compare' => 'LIKE' )); } $query->set("meta_query", $meta_query); }; } add_filter( "pre_get_posts", "custom_search_query"); //SEARCH FORM function custom_search_form( $form ) { $form = '<form role="search" method="get" id="searchform" class="searchform" action="' . home_url( '/' ) . '" > <div class="custom-form"><label class="screen-reader-text" for="s">' . __( 'Search:' ) . '</label> <input type="text" placeholder="ricerca per codice" value="' . get_search_query() . '" name="s" id="s" /> <input type="submit" id="searchsubmit" value="'. esc_attr__( 'Search' ) .'" /> </div> </form>'; return $form; } add_filter( 'get_search_form', 'custom_search_form', 40 ); //NASCONDERE PREFISSO CATEGORIA: add_filter( 'get_the_archive_title_prefix', '__return_empty_string' );
I never need default WP search, I need to search by ID, by name, and then filtering in my custom search box
Those reasonably only act on search requests. A cat && tipologie request is not a search request, so that code should not affect the resulting query. Do you have any plugins active that might impact certain requests?
Please submit the cat && tipologie form on your test site and show me the resulting SQL main query from Query Monitor. Maybe that will give me a clue about what’s happening.
Here is the main query: https://ibb.co/dPtNk2z
The query is only checking for one taxonomy term, term ID 165 (Lignano Sabbiadoro I believe). Surely this is the category you selected from the search box. No tipologie term is part of the query. The field’s PHP:
$taxonomy = wp_dropdown_categories( array( 'hierarchical'=> false, 'name'=>'tipologie', 'taxonomy' => 'tipologia', 'show_option_all'=>'Tipologia' ));
The field name is different from the taxonomy name? Unless the taxonomy has a different rewrite rule, I think you need the name to be
'tipologia'
. With that name, with “appartamento” selected and the Lignano Sabbiadoro category as well, we do get fewer pages of results than Lignano Sabbiadoro alone. In other words'name'=>'tipologia',
should be correct.You’ll notice the posts found count after the archive title shows the wrong count. It also does not mention “appartamento” at all. This is due to how the archive template is coded, but the query and the results appear to be correct. One step ahead, but you now probably need to alter how the title and posts found count on the template works.
I set as setting: ‘name’=>’tipologia’, and now it works. The only problem is that after pressing the “search” button, the selection of “tipologia” disappears and does not remain visible in the selector. However, my category selection remains visible.
The next step is to make selector n. 3, exactly like the one you see in the “search and filter plugin” search box, it sorts the results. In this specific case, it orders from the largest price to the smallest and vice versa. What is the starting point? We had already talked about it but in another context. Now the selector is inside a search box : https://test.sacconicase.com/
I started by this for the “sort by” field:
$order = wp_dropdown_categories( array( 'hierarchical'=> false, 'name'=>'sort-posts', 'id' => 'sortbox', 'onchange'=>'document.location.href=location.href+this.options[this.selectedIndex].value', 'show_option_all'=>'Ordina', 'echo'=> false ));
But it has no effect, not even shows something
The tipologia dropdown needs a “selected” arg telling it to show the value passed in the URL is shown as selected. You can get the value from the global $wp_query object using its
get()
method. You’ll need a conditional to assign0
as “selected” if $wp_query->get(‘tipologia’) returns an empty string.You might wonder “Why do I need to do this for tipologia but not category?” Because the dropdown is designed for categories. We’ve sort of hijacked it to work for tipologia. The function is not smart enough to know how to know how to get the current tipologia selection. It’s not all that predictable since it can be used in a query in a number of ways.
You cannot use wp_dropdown_categories() for a sort field because sorting is not a taxonomy. I think you’ll need to build your own select/option field. The field’s name should be “order” and the option values should be “ASC” or “DESC”. You’ll also need a couple hidden fields telling the query what to sort by. One named “meta_key” specifying which post meta key to use. Do not use “meta_value” as any field name or results will be restricted to posts with that meta value. You’ll also want a hidden field named “orderby” whose value is “meta_value_num”, assuming the meta key for sorting is price or similar numeric values.
Default sort type is alphabetic, which will list “2” after “16” just like “b” would come after “af”. We need to tell the query to treat the meta values as numeric by using “meta_value_num”.
The goal is for the resulting URL to be something like:
/lignano-sabbiadoro-appartamenti-vacanze/?tipologia=apartmento&meta_key=prezzo&orderby=meta_value_num&order=ASC&search=CercaI assumed the meta_key is “prezzo”, but it’s probably not the actual key name. Use the correct key name as the field’s value ??
About taxonomy: I already have a get() in the function:
function wpb_demo_shortcode() { $categories = wp_dropdown_categories( array( 'show_count'=> 1, 'hierarchical'=> 1, 'show_option_all'=>'Tutte le destinazioni', 'echo'=> false, )); $taxonomy = wp_dropdown_categories( array( 'hierarchical'=> false, 'name'=>'tipologia', 'taxonomy' => 'tipologia', 'show_option_all'=>'Tipologia', 'value_field'=>'slug', 'echo'=> false )); $output = '<form class="sacconi_form" method:"get" action="' . home_url( '/' ) . '">'. $categories . $taxonomy .'<br></br>'.'<input type="submit" name="search" value="Cerca">'. '</form>'; return $output; }
Probably, to start with, I should change
'value_field'=>'slug',
and putting a variable as “value field”, is it possible?No, you need a slug value in order for the “tipologia” name to work as an URL query var. You need an additional arg along the lines of:
global $wp_query; // other code here $select = $wp_query->get('tipologia'); $select = ''== $select ? 0 : $select; // use 0 value if no query var is assigned $taxonomy = wp_dropdown_categories( array( 'hierarchical'=> false, 'name'=>'tipologia', 'taxonomy' => 'tipologia', 'selected' => $select, 'show_option_all'=>'Tipologia', 'value_field'=>'slug', 'echo'=> false )); // the rest of your code
The get method (function) of the $wp_query object (
$wp_query->get()
) is unrelated to themethod="get"
attribute of the form tag. One is PHP and the other is HTML. An unfortunate and confusing coincidence of terminology.BTW, the correct operator for tag attributes is
=
, not:
. You havemethod:"get"
which is invalid. But since GET method is the default it’s of no consequence, but it’s still the wrong operator.
- The topic ‘Shortcode for runnung a search-box’ is closed to new replies.