First, I would like to say that I'm not the greatest PHP developer. That being said, I would like some input on my code. I spent an hour trying to get this to work and I finally got it to work, however, I would like to know if this is the best way to do it. I'm asking the community because I'm trying to become a better developer.
I'm building a search form that uses POST method to send values to a search page. This page then takes the values, checks the conditional statements, and updates the query based on the results.
Here is my code.
Search form code
echo '<form method="post" class="cat-search" action="'.esc_url( home_url( '/search' ) ).'" role="search" >
<div class="gender-fields">
<span class="label-wrap">
<input type="radio" name="gender" value="male" id="male">
<label for="male">Male</label>
</span>
<span class="label-wrap">
<input type="radio" name="gender" value="female" id="female">
<label for="female">Female</label>
</span>
<span class="label-wrap">
<input type="radio" name="gender" value="" id="both">
<label for="both">Both</label>
</span>
</div>
<select class="cat-letters" name="letter">
<option value="">Search by letter</option>';
foreach ( $categories as $category ) {
echo'<option value="'.$category->slug.'">'.$category->name.'</option>';
}
echo '</select>
<input class="search-submit" value="Search" type="submit" />
</form>';
Search page conditional code
$let = esc_html($_POST["letter"]);
$gen = esc_html($_POST["gender"]);
if ( !empty($_POST["gender"]) && !empty($_POST["letter"])) {
$cat_array = array($let,$gen);
$cat_string = implode("+", $cat_array);
} else if ( empty($_POST["gender"] ) ) {
$cat_string = $let;
} else {
$cat_string = $gen;
}
First, I tried to use the isset()
function instead of empty()
, but I just couldn't get it to work.
Is this the right way to do it, or is there a better way to achieve the same results?
*I never had a problem with the form, the problem was with the conditional statements.