Reputation: 1306
I'm using the following form as part of an Advanced Search page on my WordPress install.
<form action="/advanced-search/" method="get">
The form is working correctly, but producing URLs like:
/advanced-search/page/3/?act=s&f=cichlidae&g&s&c&r&tmin&tmax&hmin&hmax&pHmin&pHmax&cmin&cmax&sF&sM&aL&aD&aH
Is there any way to stop the form from sending those empty variables? In the above example only f
was searched for (value cichlidae
). As such I'd prefer it to produce a URL like this:
/advanced-search/?act=s&f=cichlidae
(plus the /page/3/
if necessary).
I can't use $_POST
because I can't get the WordPress paged
variable to work with $_POST
values.
Thanks in advance,
Upvotes: 2
Views: 1950
Reputation: 11588
Why don't you use jQuery's serialize
method to collect all the form values in a string?
$('form').submit(function() {
var string = $(this).serialize();
window.location.href = '/advanced-search/'+string;
});
It loops through all of your form elements, collects their values and converts it into a readable string format for use in URLs.
Upvotes: 2
Reputation: 67695
No, there is no way (without JavaScript that is). If there was, this would be browser-specific, since it's the browser that decides what to do with the form data.
Also, this:
foo.php?a=
...and this:
foo.php
...is semantically different. In the former, a
is passed with an empty string (""
) while the in latter, a
is not passed at all (null
).
Also, Wordpress is correct here, since the form is a search form, thus it is retrieving data and should use GET
; and not creating data as POST
should do.
A way to change this (without JavaScript) is to use a gateway script that removes empty parameters from the URL and redirect.
Per example:
$newGET = array();
foreach ($_GET as $key => $value) {
if ($value !== '') $newGET[$key] = $value;
}
header('Location: some/url?'.http_build_query($newGET));
exit;
Upvotes: 1
Reputation: 526623
Not built-in to a form, no - if the field exists, it'll be sent.
You could use Javascript to submit the form instead, and thus omit empty fields.
Upvotes: 1