I work in WordPress and Woocommerce often and this code was generated by asking the right questions for ChatGPT which is a very helpful AI.
It resides in your functions.php for your activated theme to apply to your product listings page in Woocommerce.
I needed something that would help me to pick out certain product items with a bit more granularity and this helped immensely.
Add it to your site at your own risk. I’m recording it here for my own use specifically however if you get use from it then that’s all good by me.
// woocommerce exclude category filter on all products listing page
// Add filter option to exclude products from category
add_action( 'restrict_manage_posts', 'add_exclude_category_filter' );
function add_exclude_category_filter() {
$current_cat = isset( $_GET['product_cat'] ) ? $_GET['product_cat'] : '';
$exclude_cat = isset( $_GET['exclude_category'] ) ? $_GET['exclude_category'] : '';
?>
is_admin && $query->query['post_type'] === 'product' && ! is_null( $query->query_vars['s'] ) ) {
// Check if the exclude category filter is set
if ( isset( $_GET['exclude_category'] ) && ! empty( $_GET['exclude_category'] ) ) {
$exclude_category = absint( $_GET['exclude_category'] );
$tax_query = array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $exclude_category,
'operator' => 'NOT IN',
),
);
$query->set( 'tax_query', $tax_query );
}
}
}
add_action( 'pre_get_posts', 'custom_product_query' );