Home › Forums › Product Support Forums › Ajax Search Pro for WordPress Support › Elementor WooCommerce hide empty product filters › Reply To: Elementor WooCommerce hide empty product filters
Hi Paul,
This might get a bit tricky, but it is likely possible to some extent via custom code. I have an experimental solution, which hooks into the filters and tries to restrict them to the current possible archive result set.
This is an extract from a possible feature in the upcoming version, but it should do the trick to some extent. Instructions below, but let me know if you need help with it:
function get_available_taxonomy_terms( $taxonomy ) {
global $wpdb;
// Initialize terms array
$terms = [];
$cache_key = 'terms_' . $taxonomy;
// Get the current queried object
$current_queried_object = get_queried_object();
// Check if we're on a term archive
if ( is_a( $current_queried_object, 'WP_Term' ) ) {
// Update cache key to include the term ID
$cache_key .= '_' . $current_queried_object->term_id;
// Check transient cache
$cached_terms = get_transient( $cache_key );
if ( false !== $cached_terms ) {
return $cached_terms;
}
// Get post IDs in the current category using a custom SQL query
$query = $wpdb->prepare(
"
SELECT DISTINCT tr.object_id
FROM {$wpdb->term_relationships} tr
INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
WHERE tt.taxonomy = %s
AND tt.term_id = %d
",
$current_queried_object->taxonomy, // e.g., 'category'
$current_queried_object->term_id
);
$post_ids = $wpdb->get_col( $query );
if ( empty( $post_ids ) ) {
return []; // No posts in this category, return empty array
}
// Use get_terms() to get terms associated with these post IDs
$terms = get_terms( [
'taxonomy' => $taxonomy,
'hide_empty' => false, // Include terms even if empty in other contexts
'object_ids' => $post_ids, // Filter by post IDs
'fields' => 'all',
] );
if ( is_wp_error( $terms ) ) {
$terms = [];
}
} else {
// Not a term archive, fall back to all terms for the taxonomy
$cached_terms = get_transient( $cache_key );
if ( false !== $cached_terms ) {
return $cached_terms;
}
// Get all terms for the taxonomy
$terms = get_terms( [
'taxonomy' => $taxonomy,
'hide_empty' => true, // Only include terms with associated posts
'fields' => 'all',
] );
if ( is_wp_error( $terms ) ) {
$terms = [];
}
}
// Cache the results for 1 hour
set_transient( $cache_key, $terms, HOUR_IN_SECONDS );
return $terms;
}
add_filter('asp_fontend_get_taxonomy_terms', function( $terms, $taxonomy, $args, $needed_all ){
return get_available_taxonomy_terms($taxonomy);
}, 10, 4);
Try adding this code via the Code Snippets plugin or 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.