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]
-
Compose all the HTML for what you want the shortcode to expand to. All the HTML must be collected into a single variable which is returned in the end. There are a few ways to do this. It’s common to assign an initial string fragment to a variable, then concatenate additional HTML as needed to the same variable with the
.=
operator. For example:$content = '<form action="https://example.com/search-results/">'; $content .= '<select name="pick-one"><option value="1">Foo</option></select>; $content .= '<input type="submit">'; $content .= '</form>'; return $content;
That will let you place a search form in content, but it doesn’t do any searching. You’ll need to develop code to handle the submitted data, do the search query, and output the results. The default
s
query var will cause WP to do a basic content search, but if you need to include additional search parameters, you need to either expand the default functionality, or manage your search independent of what WP does by default.- This reply was modified 1 year, 2 months ago by bcworkz. Reason: code format fixed
Ok. But maybe the example is not complete? I mean that the code broke the site
Sorry, syntax error. Correct line:
$content .= '<select name="pick-one"><option value="1">Foo</option></select>';
In any case, this was intended to be an illustrative example, not necessarily functional code. My bad for not making that clear.
You should expect to need to do some debugging of any code you see online. Do you use a syntax highlighting code editor? You should. Entering code into a forum editor makes it more difficult to spot typos. Once entered into a code editor the error becomes more apparent because code after the typo isn’t highlighted correctly. You’ll find all sorts of suggestions for a good code editor that works with your O/S by doing a little searching.
I wonder if I can develop this shortcode customizing the default WP search box, whose code I found in a tutorial, so I mixed the 2 functions and got
function wpb_demo_shortcode($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" value="' . get_search_query() . '" name="s" id="s" /> <input type="submit" id="searchsubmit" value="'. esc_attr__( 'Search' ) .'" /> </div> </form>'; return $form; } } // register shortcode add_shortcode('ricerca', 'wpb_demo_shortcode');
This is working but I dont want the default WP search, so I would begin with changing the imput, i.e. a select fot selecting the categories, then I have to remove all what’s related to WP search, all with “s”, any advice to make this transformation?
of course I have to remove
<input type="text" value="' . get_search_query() . '" name="s" id="s" />
You need to change the values for the input attributes
name="s" id="s"
. Not necessarily remove the field, unless you don’t want a free-form text input. But there needs to be something in the form data telling WP to make the appropriate query. If field names can supply all of the appropriate query vars, that will suffice. Or you can whitelist your own custom query var through the “query_vars” filter that would decidedly indicate that a custom search query should be made. You can then use “pre_get_posts” action to manipulate query vars to get the results you want.Another option would be to set the form’s action URL to go to a particular page which has a custom template which contains appropriate code to make the search query and display results.
I’m trying another approach. I’d like to start from a simple but complete search box. I start from a selector that lets me choose among all the default wp categories
I coded this:
function wpb_demo_shortcode() { $categories = get_categories(); $output = '<form method:"get" action="' . home_url( '/' ) . '">.<input select value="$categories" style="border-color:grey";>.</form>'; echo $output; }
First of all
get_categories()
doesnt show what I’d like to show, that is to say a dropdown list of all wp categories. I have a little bit familiarity with selectors but in this case I cant call the optionssecond (little) point: the style, I’d like to have the same style of the fields you can see in the search and filter plugin box: https://test.sacconicase.com/case-vacanza/italia/toscana/marina-di-massa-appartamenti-vacanze/
style=”border-color:grey” is not what I expected
To use get_categories(), you’d need to loop through the returned term objects and generate the option list very similar to how we’d loop through posts to generate a posts archive. There’s no need to go through all of that though. You can get a dropdown list of categories with wp_dropdown_categories(). It does all of what I’ve just described for you.
I’m going to contradict what I said in another topic about element styles. You should try to avoid them when possible. In that other topic we were talking about a back end form. Admin styles are more difficult to apply and you just wanted a simple font-weight style applied. This is a different situation. For front end styling it’s best to avoid element style attributes, it makes future re-styling more difficult. Try to achieve all styling with CSS alone.
If you want styling similar to an existing form, use the same class attributes used in the form whose style you want to replicate. You may need to create additional CSS to address certain styling that cannot be replicated by reusing the same classes.
OK. I’m putting more parameters, but only the first one in working (about the count)
function wpb_demo_shortcode() { $categories = wp_dropdown_categories('show_count=>1', 'hierarchical=>1','show_option_all=>Tutte le destinazioni'); $output = '<form class="sacconi_form" method:"get" action="' . home_url( '/' ) . '"> </form>'; echo $output; }
All args for wp_dropdown_categories() need to be in a single array.
Your quotes do not close correctly.'show_count=>1'
and its ilk are not single strings like you are doing, they are array key/value pairs.
$categories needs to be within the form or its selection will not be sent.
Shortcode handlers should never echo out content. Content should be returned instead. Your code will be easier to read and maintain if it were better formatted.function wpb_demo_shortcode() { $categories = wp_dropdown_categories( array( 'show_count'=> 1, 'hierarchical'=> 1, 'show_option_all'=>'Tutte le destinazioni', 'echo'=> false, )); $output = '<form class="sacconi_form" method:"get" action="' . home_url( '/' ) . '">'. $categories . '</form>'; return $output; }
I realize this is a work in progress and not yet a complete form, but there’s no way right now to submit the form. If you did so, the form as it is will just make a category archive request like
https://example.com/?cat=123
. It would be the expected response. As long as any additional fields you add all end up as proper query var args this will work.Ok, I put a button, now it’s working:
function wpb_demo_shortcode() { $categories = wp_dropdown_categories( array( 'show_count'=> 1, 'hierarchical'=> 1, 'show_option_all'=>'Tutte le destinazioni', 'echo'=> false, )); $output = '<form class="sacconi_form" method:"get" action="' . home_url( '/' ) . '">'. $categories . '<input type="submit" name="sacconi_search" value="Cerca">'. '</form>'; return $output; }
The second step is setting a custom taxonomy selector, like the second field of my search and filter form https://test.sacconicase.com/ , where you read “tipologia”, the relation beween all the fields must be “AND”. I suppose I have to define another $, as I did for categories, with an array, but the hook will be different from “
wp_dropdown_categories
“. So which tools have I to use?You can pass a “taxonomy” arg to wp_dropdown_categories() to cause it to list custom taxonomies instead of categories. Also use the “name” arg to specify the taxonomy name as well. This prevents the default “cat” name from being used. The resulting submission URL should be something like
example.com/?cat=123&my-tax-name=456Taxonomy name as query var is actually deprecated but I think it will still work. The two fields are actually supposed to be combined into a “tax_query” arg array. Using “tax_query” does give us much more flexibility in accepted data and applied logic, but it’s more complicated to set up as well. Fortunately you want AND logic which is the default. If you wanted OR logic we’d have to use “tax_query”.
I’m progressing but not in the right directions:
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( 'show_count'=> 1, 'name'=> 'Tipologie' )); $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; }
Now I see 3 selectors: https://test.sacconicase.com/case-vacanza/italia/toscana/marina-di-massa-appartamenti-vacanze/
It is also important that the taxonomy count is coordinated with the category count, as happens in the search and filter plugin box. But maybe they achieve this with java? Or can I also do it just with php?
Example: If in Marina fi Massa (category) there are 42 accommodations in total, then in the apartment type selector (taxonomy), I will see the number 32 next to apartments, that is to say the number of apartments only in Marina di MassaUnfortunately, the various calls to wp_dropdpown_categories() do not relate to each other. The counts shown are for all posts assigned a particular term regardless of what other terms are selected in other fields. The eventual query uses AND logic but the counts shown do not.
It’s really infeasible to show counts that reflect the current filter selections in the fields themselves. People don’t necessarily select terms in the order presented. Every time someone picks something we’d need to update all the terms in all the fields if we are to be consistent with this paradigm. It would be a slow, resource intensive process.
In order to give users feedback on the effectiveness of their selected terms, I suggest no showing counts in the dropdowns and instead have a “nn matching properties found” message at the top which is updated after each selection is made. Not exactly the same kind of feedback, it’s sort of one step behind instead. But it’s still good feedback and way more feasible to implement.
In order to update the “nn” count in the message after each selection, you would want to make an Ajax request via JavaScript to make a count query of the currently selected fields combined.
Ok, I tryed with
'name'=>'taxTerm'
to show all the terms of the taxonomy but it doesnt workFor the taxonomy selector I should use also something like
'echo'=> false,
because I see 3 selectors, and one out of the form (I should have just 2), but this breacks the site. My custom search form is in the lowest part of the right sidebar: https://test.sacconicase.com/
The name needs to be what ever the registered taxonomy slug is, the first arg when register_taxonomy() was called. The “taxonomy” arg also needs the save value passed.
You do need to suppress echoing, if adding the “echo” arg breaks the site, you’ve likely introduced a syntax error somehow. The error message should give you an idea of what went wrong. Error messages can be difficult to interpret sometimes. Try searching the internet with the message. Often a better explanation can be found.
If you still have difficulty, post your code and maybe I can spot the problem.
- The topic ‘Shortcode for runnung a search-box’ is closed to new replies.