Home › Forums › Product Support Forums › Ajax Search Pro for WordPress Support › Dynamic categories filtering › Reply To: Dynamic categories filtering
November 25, 2021 at 5:11 pm
#35737
Keymaster
In this case the only possible solution is to use a custom code – as there is no other way to force including all child terms.
I have constructed a small code snippet. All you need to edit is the $my_custom_fitlers array variable. I have included some explanation on how to use it.
For this to work, you must remove the existing filter, as the code will ad itt programmatically.
add_action('asp_pre_parse_filters', 'asp_add_my_own_filters', 10, 2);
function asp_add_my_own_filters($search_id, $options) {
// This is the array of rules
$my_custom_filters = array(
array(
'search_id' => 1, // For which search ID should this filter exist
'taxonomy' => 'category', // Taxonomy name
'parent_id' => 25, // Parent term (category) ID for which include the child terms
'label' => 'Label', // The filter label
'type' => 'checkboxes', // The filter type
'selected' => true // Should the items be selected or not
),
array(
'search_id' => 2,
'taxonomy' => 'category',
'parent_id' => 26,
'label' => 'Label',
'type' => 'checkboxes',
'selected' => true
)
);
// --- DO NOT CHANGE ANYTHING BELOW ----
foreach( $my_custom_filters as $f ) {
if ( $f['search_id'] == $search_id ) {
// Creating a new filter
$filter = wd_asp()->front_filters->create(
'taxonomy',
$f['label'],
$f['type'],
array(
'taxonomy' => $f['taxonomy']
)
);
$terms = array( get_term_by('id', $f['parent_id'], $f['taxonomy']) );
$children = get_term_children($f['parent_id'], $f['taxonomy']);
$terms = array_merge($terms, get_terms(array(
'hide_empty' => false,
'taxonomy' => $f['taxonomy'],
'include' => $children
)));
$termsHierarchical = array();
wd_sort_terms_hierarchicaly($terms, $termsHierarchical);
wd_flatten_hierarchical_terms($termsHierarchical, $terms);
foreach( $terms as $term ) {
// Add each taxonomy terms one by one
$filter->add(array(
'id' => $term->term_id,
'label' => $term->name,
'level' => $term->level,
'taxonomy' => $f['taxonomy'],
'default' => false,
'parent' => $f['parent_id'],
'selected' => $f['selected']
));
}
$filter->selectByOptions($options);
wd_asp()->front_filters->add($filter);
}
}
}
Try adding this code to the functions.php file in your theme/child theme directory – make sure to have a full server back-up first for safety. For more details you can check the safe coding guidelines.