How to apply WooCommerce category order while using visual attributes filtering
Sorting WooCommerce products is an easy job, specific area ordering is possible after selecting the appropriate taxonomy or attribute. When using mix of multiple taxonomies or/and attributes a sort is still easy to create through advanced set-up
Sometimes, there’s no need to apply a very specific order for all those areas, as it become impractical and hard to maintain. Might be a better approach to use a simple sorting which apply to categories, even if there’s additional visual filters used.
The following image illustrate a category instance where the customized order is applied accordingly. There is no visual filter used so far.
When making a selection on the left filters, the internal WordPress query changes and will not match the simple category ordering anymore. It will try to locate an advanced sort which include the appropriate settings (e.g. selected category, selected filter etc). If none are found, the default query order is returned.
The above, is still a category area, but using additional filters. There’ still possible to use the simple category order and apply to above, without creating customized order for each of possible combinations. This can be achieved easily by enabling the functionality through the “Use category order for WooCommerce when apply filters” option, available at admin dashboard > Settings > Post Types Order:
The feature is available starting version 4.2.
For older versions this can be implemented through a filter ‘apto/query_filter_valid_data’. The following code should be used along with theme functions.php :
add_filter('apto/query_filter_valid_data', 'custom_woocommerce_query_filter_valid_data', 99); function custom_woocommerce_query_filter_valid_data( $query ) { if (!in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) return $query; $tax_data = $query->tax_query->queries; if(isset($tax_data['relation'])) unset($tax_data['relation']); $found = FALSE; //ensure the query include a product_cat taxonomy foreach( $tax_data as $key => $item_tax_data ) { if ( !isset ( $item_tax_data['taxonomy'] ) ) return $query; if ( $item_tax_data['taxonomy'] != 'product_cat' ) continue; if( count((array)$item_tax_data['terms']) != 1 ) return $query; $found = TRUE; } if ( $found === FALSE ) return $query; //unest all other taxonomies foreach ( $query->tax_query->queries as $key => $item_tax_data ) { if ( ! is_int($key) ) continue; if ( $item_tax_data['taxonomy'] != 'product_cat' ) unset ( $query->tax_query->queries[$key] ); } return $query; }