Search code examples
phpwordpressdropdown

On clear filters button click, set all dropdown lists to default values in php


I am new to PHP and WordPress. I am using 2 dropdown lists, one for filter categories and other for sort by purpose. And for sorting and filtering, I have not used any hooks. The following code for filter and sortby implementation and another code snippet I am using for dropdown :

if($categoryFilter && $categoryFilter == 'all' && $searchKey == '' ) {

    $order = 'DESC';
    if($sortbyFilter == 'best_match') $order = 'ASC';

    $args = array(
        'post_type' => array('auction-detail','lot','asset'),
        'post_status' => 'publish',
        'orderby'     => 'date', 
        'order' => $order,
        'posts_per_page' => 10,
        'paged' => $paged
    );
    query_posts( $args );
}

if($categoryFilter && $categoryFilter != 'all' && $searchKey == '' ) {
    $sortbyFilter = 'newly_listed';
    $_POST['sortby-filter'] = $sortbyFilter;
    $args = array(
        'post_type' => array('lot','asset'),
        'post_status' => 'publish',
        //'orderby'     => 'post_title', 
        //'order' => 'ASC',
        'posts_per_page' => 10,
        'paged' => $paged,
        'tax_query' => array(
            array(
                'field' => 'slug',
                'terms' => $categoryFilter,
                'taxonomy'  => 'category'
            )
        )
    );
    query_posts( $args );
}



<div class="filterCols category">
<select id="selcategories" name="category" onchange="handleChange()">
<option value='all' <?php echo (isset($categoryFilter) && $categoryFilter 
== 'all') ? 'selected="selected"' : ''; ?>>All</option>
<option value='commercial_trucks' <?php echo (isset($categoryFilter) && 
$categoryFilter == 'commercial_trucks') ? 'selected="selected"' : ''; ? 
>>Heavy Machinary</option>
<option value='farm_machinery_implements' <?php echo 
(isset($categoryFilter) && $categoryFilter == 
'farm_machinery_implements') ? 'selected="selected"' : ''; ?>>Farm 
Equipment</option>
<option value='na' <?php echo (isset($categoryFilter) && $categoryFilter 
== 'na') ? 'selected="selected"' : ''; ?>>Construction Equipment</option>
</select>
<input hidden name="category-filter" id="category-filter" type="text" 
value="<?php echo $_SESSION['category']; ?>" />
</div>


Below is clear filter div :

<div class="filterCols sortby clearBtnWrapper">
<i class="fa fa-refresh" ></i><a href="#">Clear All</a></div>

I have tried with remove_all_filters() but couldn't get any luck as there are no hooks. Is there any way around?


Solution

  • I don't see your Clear Filters button nor the second select in your question, but how about using something like:

    <button onclick="clearFilters()">CLEAR FILTERS</button>
    

    And then in your .js or inline script

    function clearFilters(){
        jQuery('#selcategories').val('all');
        jQuery('#sortbyFilter').val('all');
    }