'Filter by Brand', 'show_count' => 'yes' ), $atts); // Check if WooCommerce is active if (!class_exists('WooCommerce')) { return '
WooCommerce is not active
'; } // First, let's check what taxonomies exist $taxonomies = get_object_taxonomies('product'); // Try different possible brand taxonomy names $brand_taxonomy = ''; $possible_names = array('product_brand', 'pa_brand', 'pwb-brand', 'yith_product_brand'); foreach ($possible_names as $tax_name) { if (in_array($tax_name, $taxonomies)) { $brand_taxonomy = $tax_name; break; } } if (empty($brand_taxonomy)) { return ''; } // Get terms hierarchically - get ALL terms first, then filter manually $all_terms = get_terms(array( 'taxonomy' => $brand_taxonomy, 'hide_empty' => false, // Get all terms, we'll filter manually 'orderby' => 'name', 'order' => 'ASC' )); if (is_wp_error($all_terms) || empty($all_terms)) { return ''; } // Organize terms hierarchically - only include terms with products $parent_terms = array(); $child_terms = array(); foreach ($all_terms as $term) { // Check if term has published products and get accurate count (regardless of stock status) $product_query = new WP_Query(array( 'post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => -1, // Get all to count them 'fields' => 'ids', // Only get IDs for performance 'tax_query' => array( array( 'taxonomy' => $brand_taxonomy, 'field' => 'term_id', 'terms' => $term->term_id, 'include_children' => false ) ) )); $actual_count = $product_query->found_posts; wp_reset_postdata(); if ($actual_count > 0) { // Store the actual count in the term object $term->actual_count = $actual_count; if ($term->parent == 0) { $parent_terms[] = $term; } else { if (!isset($child_terms[$term->parent])) { $child_terms[$term->parent] = array(); } $child_terms[$term->parent][] = $term; } } } // Filter out parent terms that have no products themselves AND no child terms with products $filtered_parent_terms = array(); foreach ($parent_terms as $parent) { $has_products = isset($parent->actual_count) && $parent->actual_count > 0; $has_children_with_products = isset($child_terms[$parent->term_id]) && !empty($child_terms[$parent->term_id]); // Include parent if it has products OR if it has children with products if ($has_products || $has_children_with_products) { $filtered_parent_terms[] = $parent; } } $parent_terms = $filtered_parent_terms; ob_start(); ?> 'Display product brands for filtering') ); } public function widget($args, $instance) { $title = !empty($instance['title']) ? $instance['title'] : 'Filter by Brand'; echo $args['before_widget']; echo do_shortcode('[brand_filter title="' . esc_attr($title) . '"]'); echo $args['after_widget']; } public function form($instance) { $title = !empty($instance['title']) ? $instance['title'] : 'Filter by Brand'; ?>sanitize_text_field($new_instance['title']) ); } } // Initialize new Shoptimizer_Brand_Filter_Fixed();