The default product category filter in the WooCommerce admin panel is limited to the product_cat
taxonomy, causing inefficiencies for sites using custom taxonomies for product categorization.
The proposed solution is a WordPress function that replaces the default filter with a custom taxonomy filter in the WooCommerce Admin Products list. This function modifies the ‘no selection‚ value from -1
to an empty string, which avoids interference from the custom taxonomy with the search query when no option is selected.
By commenting and uncommenting specific lines of code within the function, it is possible to add the custom taxonomy dropdown instead of replacing the default one. This change facilitates a more efficient and customizable admin experience in WooCommerce stores.
add_filter( 'woocommerce_product_filters', 'bubdev_woo_modify_admin_product_filters' );
/**
* Replace Woo Admin Columns Product Category Filter
*
* Replaces the default product category filter with a custom taxonomy filter in
* the WooCommerce Admin Products list. It also adjusts the 'no selection'
* value in the dropdown from '-1' to an empty string to prevent the custom
* taxonomy from interfering with the search query when no option is selected.
*
* @param string $output The default HTML output for the WooCommerce product filters.
* @return string Modified HTML output with the custom taxonomy filter.
*/
function bubdev_woo_modify_admin_product_filters( $output ) {
if ( ! is_admin() || ! get_post_type() === 'product' ) return;
global $wp_query;
$taxonomy = 'bub_product_cat';
$selected = isset( $wp_query->query_vars[$taxonomy] ) ? $wp_query->query_vars[$taxonomy] : '';
$info_taxonomy = get_taxonomy( $taxonomy );
// Render the custom taxonomy dropdown.
$custom_dropdown = wp_dropdown_categories(array(
'show_option_none' => __("Nach {$info_taxonomy->label} filtern"), // changed
'taxonomy' => $taxonomy,
'name' => $taxonomy,
'order' => 'ASC',
'class' => 'dropdown_bub_product_cat',
'echo' => false, // <== Needed in a filter hook
'tab_index' => '2',
'selected' => $selected,
'show_count' => true,
'hide_empty' => true,
'value_field' => 'slug',
));
// Replace the 'value="-1"' or 'value=\'-1\'' (default for 'show_option_none')
// with 'value' (without a value) to prevent the 'bub_product_cat=-1'
// parameter from being added to the search query when no option is selected.
// The replacement is precisely targeting the 'show_option_none' option.
$custom_dropdown = preg_replace( "/<option value=('|\")-1('|\")>/", '<option value>',
$custom_dropdown );
// Add after default category filter (= before product type filter).
// $after = '<select name="product_type"';
// $output = str_replace( $after, $custom_dropdown . $after, $output );
// Replace default category filter.
$output = preg_replace( '/<select(.+?)product_cat(.+?)<\/select\>/s', $custom_dropdown, $output );
return $output;
}