# Frontend filters API

## Changing filter values within a filter box

To access and change the values of filter items use the *asp\_pre\_get\_front\_filters* hook, as following:

```php
add_filter('asp_pre_get_front_filters', 'asp_change_a_filter', 10, 2);
function asp_change_a_filter($filters, $type) {
  foreach ($filters as $k => &$filter) {
    // To check some of the attributes:
    // $filter->label
    // $filter->display_mode
    // $filter->position
    // $filter->id
    // $filter->type() >> returns the filter type
    // $filter->field() >> field that is filtered (if applicable)
    // do a var_dump($filter->data) -> to see the filter data
    
    // Go through the filter items via a loop
    foreach ($filter->get() as $kk => $item) {
      // Changing a filter attribute: label, selected, value, default by array ID
      $filter->attr($kk, 'label', 'New Label', true);

      // Remove the current item by array ID
      $filter->remove($kk, true);
    }
    
    // You can also change/remove items by key, without a loop
    // ..for a category/term filter, use the term ID
    $filter->attr(123, 'label', 'New Label');
    $filter->remove(123);
    // ..for a custom field filter, use the field value
    $filter->attr('value', 'label', 'New Label');
    $filter->remove('value'); 

    // Remove values from a custom field filter
    if ( $filter->type() == 'custom_field' && $filter->field() == 'my_field' ) {
      $filter->remove(array('value1', 'value2'));
    }    
    // Adding a new value to a custom field filter
    if ( $filter->type() == 'custom_field' && $filter->field() == 'my_field' ) {
      $filter->add(array(
        'label' => 'Value label 1',
        'selected' => false,
        'value' => 'value1'
      ));
      
      // The second function argument allows setting the value position
      // Adding a value after the 2nd option
      $filter->add(array(
        'label' => 'Value label 2',
        'selected' => false,
        'value' => 'value2'
      ), 2);
      
      // Adding a value to before the last option
      $filter->add(array(
        'label' => 'Value label 3',
        'selected' => false,
        'value' => 'value3'
      ), -1);
    }    
  }
  return $filters;
}
```

## The WD\_ASP\_FrontFilters singleton class

This API should be used to manage the front-end filter boxes. The class methods can be used to add/remove/modify/find any front-end filter box.

### Source

File: `wp-content/plugins/ajax-search-pro/includes/classes/core/class-asp-frontfilters.php`

The front-end filter management is encapsulated within the **WD\_ASP\_FrontFilters** class, and it's instance can be accessed via the..

```php
wd_asp()->front_filters
```

..variable, or if you prefer your own, then:

```php
$my_variable = WD_ASP_FrontFilters::getInstance();
```

### Usage

For usage examples, please see the [chapter below](https://documentation.ajaxsearchpro.com/plugin-api/front-end-filters-api#examples).

Filters should be added, changed and removed exlusively within the **asp\_pre\_parse\_filters** and **asp\_post\_parse\_filters** action hooks. Using any other hooks may result in a malfunction.

Example of changing and removing certain filters by their labels:

```php
add_action('asp_post_parse_filters', 'asp_change_the_filters', 10, 2);
function asp_change_the_filters($search_id, $options) {
    if ( $search_id == 1 ) {
        // Change filter position to 1
        wd_asp()->front_filters->set("Test drop", 'position', 1);
        // Change filter label
        wd_asp()->front_filters->set("Test drop", 'label', 'My test drop');
        // Remove a filter by label
        wd_asp()->front_filters->remove("Filter by Product categories");
    }
}
```

Example of adding a custom taxonomy filter:

```php
add_action('asp_pre_parse_filters', 'asp_add_my_own_filters', 10, 2);
function asp_add_my_own_filters($search_id, $options) {
    if ( $search_id == 1 ) {
        // Creating a new filter
        $filter = wd_asp()->front_filters->create(
            'taxonomy',
            'My Taxonomy Filter',
            'dropdown',
            array(
                'taxonomy' => 'category'
            )
        );
        // Adding the select all option first
        $filter->add(array(
            'id' => 0,
            'label' => 'Select all',
            'default' => true,
            'selected' => true
        ));
        // Getting the terms to add
        $terms = get_terms("category", array(
            'hide_empty' => false,
            'fields' => 'id=>name'
        ));
        foreach( $terms as $id => $name ) {
            // Add each taxonomy terms one by one
            $filter->add(array(
                'id' => $id,
                'label' => $name,
                'taxonomy' => 'category',
                'default' => false,
                'selected' => false
            ));
        }
        /**
         * Make sure to change the filter options, if there was a
         * redirection to the results page.
         **/ 
        $filter->selectByOptions($options);
        /**
         * Optionally, you can change the filter position as well, via:
         * $filter->position = 1;
         **/
        // Finally, append the filter
        wd_asp()->front_filters->add($filter);
    }
}
```

For methods list and examples, please check below.

## Methods list

### create()

```php
create(string $type, string $label = '', string $display_mode = '', array $data = array())
```

Creates and returns a new filter object, depending on the **$type** variable. This **will not add** the filter automatically to the filters list, only creates a new object. The filter has to be added via the `add($filter)` method after.

#### Parameters

* **$type** *(string)* - The filter type, can be: *taxonomy*
* **$label** *(string)* (optional) - The filter box header label
* **$display\_mode** (*string*) (optional) - The display mode of the filter values: checkboxes, input, slider, range, dropdown, radio, dropdownsearch, multisearch
* **$data** (*array*) (optional) - Additional data, that may be required within the template for this filter depending on the **$type** and **$display\_mode**\
  Check the examples below for the usage.

#### Return values

* (*aspFilter | aspCfFilter | aspTaxFilter*) The new filter object

### add()

```php
add( aspFilter $filter )
```

Adds the final $filter object to the front-end filters list.

#### Parameters

* (aspFilter) **$filter** - The filter object to add to the front-end filters list

#### Return values

* (*aspFilter | aspCfFilter | aspTaxFilter*) The new filter object

### set()

```php
set( int|string $key, string $attribute, mixed $value )
```

Finds a filter by title or ID ($key) and changes it's attribute.

#### Parameteres

* **$key** (*int|string*) - Filter ID or filter label text
* **$attribute** (*string*) - Filter attribute: *label, display\_mode, data, position*
* **$value** (*mixed*) - Value to change the attribute to

#### Return values

* (bool) true|false - True, when the change was successful, false otherwise.

### get()

```php
get( string $order = 'position', $type = false )
```

Gets the registered filters by the given order and the given type

#### Parameteres

* **$order** (*string*)(optional) - position or added
* **$type** (*bool | string*)(optional) - filter type: taxonomy, custom\_field or boolean false for everything

#### Return values

* array - Array of front-end filters

### remove()

```php
remove( int|string $key )
```

Removes a filter from the front-end filters list, based on the ID or filter label.

#### Parameters

* **$key** (*int|string*) - Filter ID or filter label text

#### Return values

* (bool) true|false - True, when the removal was successful, false otherwise.

### Examples

#### Adding custom taxonomy filter

The example below displays adding a custom taxonomy filter, with a select all option. The commented sections contain the possible parameters for this type of filter.

```php
add_action('asp_pre_parse_filters', 'asp_add_my_own_filters', 10, 2);
function asp_add_my_own_filters($search_id, $options) {
    if ( $search_id == 1 ) {
        $filter = wd_asp()->front_filters->create(
            'taxonomy',                // Filter type
            'My Product cat filter',   // Filter box label 
            'checkboxes',              // Display mode: checkboxes, dropdown, dropdownsearch, multisearch, radio
            array(
                'taxonomy' => 'category',
                // allowing CPT results that does not match the terms from this taxonomy
                'allow_empty' => false, 
                'logic' => 'or' // or, and,
            )
        );
        // The select all must have the ID = 0
        $filter->add(array(
            'id' => 0,
            'label' => 'Select All',
            'default' => true,
            'selected' => true
        ));
        $filter->add(array(
            'id' => 81,
            'label' => 'Clothing',
            'taxonomy' => 'category',
            'default' => true,
            'selected' => true
        ));
        $filter->add(array(
            'id' => 84,
            'label' => 'Posters',
            'taxonomy' => 'category',
            'default' => true,
            'selected' => true
        ));
        /**
         Another variation, by adding all categories
            $terms = get_terms("category", array(
                'hide_empty' => false,
                'fields' => 'id=>name'
            ));
            foreach( $terms as $id => $name ) {
                $filter->add(array(
                    'id' => $id,
                    'label' => $name,
                    'taxonomy' => 'category',
                    'default' => false,
                    'selected' => false
                ));
            }
        */    
    
        $filter->selectByOptions($options);
        wd_asp()->front_filters->add($filter);
    }
}
```

#### Dropdown, checkbox and radio type custom field filters

```php
// --------------------------------
// Drop down filter example - for WooCoomerce stock status
// --------------------------------
add_action('asp_pre_parse_filters', 'asp_add_my_own_filters', 10, 2);
function asp_add_my_own_filters($search_id, $options) {
    if ( $search_id == 1 ) {
        // Dropdown
        $filter = wd_asp()->front_filters->create(
            'custom_field',
            'Dropdown stock test',
            // Type: dropdown, dropdownsearch, multisearch or radio
            'dropdown',
            array(
                'field' => '_stock_status',
                /**
                 * Operators list:
                 *  String
                 *     like  => string matching anywhere
                 *     elike => string matching exactly
                 *  Numeric
                 *     eq   => equals '='
                 *     neq  => not equal '<>'
                 *     lt   => less '<'
                 *     let  => less or equals '<='
                 *     gt   => greater '>'
                 *     get  => greater or equals '>='
                 */
                'operator' => 'like',
                // only applies on 'dropdown' type (multiselect for dropdown)
                'multiple' => true,
                // or or and, only applies for 'multisearch' or 'dropdown' + multiple
                'logic' => 'or',
                // allow match if this custom field is unset
            )
        );
        $filter->add(array(
            'label' => 'Any stock (empty val)',
            'value' => '',
            'selected' => true,
            'default' => true
        ));
        $filter->add(array(
            'label' => 'Any stock (multi val)',
            'value' => 'instock::outofstock',
            'selected' => true,
            'default' => true
        ));
        $filter->add(array(
            'label' => 'In Stock',
            'value' => 'instock',
            'selected' => true,
            'default' => true
        ));
        $filter->add(array(
            'label' => 'Out of Stock',
            'value' => 'outofstock',
            'selected' => false,
            'default' => false
        ));
        $filter->selectByOptions($options);
        wd_asp()->front_filters->add($filter);
    }
}
```

#### Text and hidden type custom field filters

```php
// --------------------------------
// Text or hidden filter example
// --------------------------------
add_action('asp_pre_parse_filters', 'asp_add_my_own_filters', 10, 2);
function asp_add_my_own_filters($search_id, $options) {
    if ( $search_id == 1 ) {
        $filter = wd_asp()->front_filters->create(
            'custom_field',
            'Text stock',
            // text or hidden
            'text',
            array(
                'field' => '_stock_status',
                // See operator list on above example
                'operator' => 'elike'
            )
        );
        $filter->add(array(
            'label' => 'Stock status',
            'value' => 'instock',
            'default' => 'instock'
        ));
        $filter->selectByOptions($options);
        wd_asp()->front_filters->add($filter);
    }
}
```

#### Date type custom field filter

```php
// --------------------------------
// Date filter example
// --------------------------------
add_action('asp_pre_parse_filters', 'asp_add_my_own_filters', 10, 2);
function asp_add_my_own_filters($search_id, $options) {
    if ( $search_id == 1 ) {
        $filter = wd_asp()->front_filters->create(
            'custom_field',
            'Date test',
            'datepicker',
            array(
                'field' => '_date',
                'placeholder' => '',
                // The display date format
                'date_format' => 'dd/mm/yy',
                /**
                 * Date storage format (how the field contains the date)
                 *  datetime  => standard datetime format, ex.: 2001-03-10 17:16:18
                 *  timestamp => timestamp format, ex.: 1561971794
                 *  acf       => custom ACF format (YYYYMMDD): 20191231
                'date_store_format' => 'datetime'
            )
        );
        $filter->add(array(
            'label' => 'Date test',
            /**
             * Static values
             * '31/07/2019' => use this format only, DD/MM/YYYY
             * Relative values
             * ''         => no value displayed
             * '+0'       => current date
             * '+3m +4d'  => 3 months and 4 days from now
             * '-2m -10d' => 2 months and 10 days before now
            'value' => '',
            'default' => ''
        ));
        $filter->selectByOptions($options);
        wd_asp()->front_filters->add($filter);
    }
}
```

#### Slider and Range slider custom field filter

```php
// --------------------------------
// Slider filter example
// --------------------------------
add_action('asp_pre_parse_filters', 'asp_add_my_own_filters', 10, 2);
function asp_add_my_own_filters($search_id, $options) {
    if ( $search_id == 1 ) {
        $filter = wd_asp()->front_filters->create(
            'custom_field',
            'Price slider <=',
            'slider',
            array(
                'field' => '_price',
                'slider_prefix' => '-,',
                'slider_suffix' => '.',
                'slider_step' => 1,
                'slider_from' => 1,
                'slider_to'   => 1200,
                'slider_decimals' => 0,
                'slider_t_separator' => ' ',
                /**
                 * Operators list:
                 * eq   => equals '='
                 * neq  => not equal '<>'
                 * lt   => less '<'
                 * let  => less or equals '<='
                 * gt   => greater '>'
                 * get  => greater or equals '>='
                 */
                'operator' => 'let'
            )
        );
        $filter->add(array(
            'value' => 300,
            'default' => 300
        ));
        $filter->selectByOptions($options);
        wd_asp()->front_filters->add($filter);
    }
}

// --------------------------------
// Range slider filter example
// --------------------------------
add_action('asp_pre_parse_filters', 'asp_add_my_own_filters', 10, 2);
function asp_add_my_own_filters($search_id, $options) {
    if ( $search_id == 1 ) {
        $filter = wd_asp()->front_filters->create(
            'custom_field',
            'Price range filter',
            'range',
            array(
                'field' => '_price',
                'range_prefix' => '-,',
                'range_suffix' => '.',
                'range_step' => 1,
                'range_from' => 1,
                'range_to'   => 1200,
                'range_decimals' => 0,
                'range_t_separator' => ' '
            )
        );
        $filter->add(array(
            'label' => 'Clothing',
            'value' => array(20, 1180),
            'default' => array(20, 1180)
        ));
        $filter->selectByOptions($options);
        wd_asp()->front_filters->add($filter);
    }
}
```
