✨ Professional WordPress development, custom website builder, efficient on-line, cooperate and enjoy optimization services! 🚀
In WooCommerce, you can use the following PHP code to "Empty all products in a specific category with one click".
// 1. Define the delete function first
function delete_all_products_in_category($category_slug_or_id) {
$args = [
'post_type' => 'product',
'posts_per_page' => -1,
'post_status' => 'any',
'tax_query' => [
[
'taxonomy' => 'product_cat', 'field' => is_new_cat', 'field' => is_new_cat
'field' => is_numeric($category_slug_or_id) ? 'term_id' : 'slug', 'field' => is_numeric($category_slug_or_id) ?
'terms' => $category_slug_or_id,
]
]
]
$products = get_posts($args);
$deleted = 0;
foreach ($products as $product) {
wp_delete_post($product->ID, true); // force permanent delete
$deleted++;
}
return $deleted;
}
// 2. Add the menu
add_action('admin_menu', function() {
add_submenu_page(
'woocommerce', 'empty product categories', 'add_submenu_page'
'Empty product categories', 'manage_woocommerce', 'manage_wooocommerce', 'manage_woocommerce'
'manage_woocommerce', 'delete-products-by-category', 'delete-products-by-category'
'delete-products-by-category', 'render_delete_products-by-category'
'render_delete_products_page'
);
});
// 3. Render the page, using the function defined above
function render_delete_products_page() {
$deleted_count = null;
if (isset($_POST['product_cat_slug'])) {
$cat = sanitize_text_field($_POST['product_cat_slug']);
$deleted_count = delete_all_products_in_category($cat);
}
? >
<div class="wrap">
<h1>Clear WooCommerce Categories</h1>
<form method="post" action="">
<p>
<label for="product_cat_slug">Enter the category Slug or ID:</label><br>
<input type="text" name="product_cat_slug" id="product_cat_slug" style="width:300px;" required>
</p>
<p>
<button class="button button-primary" type="submit">Delete all products under this category immediately</button>
</p>
<input type="hidden" name="trp-form-language" value="en"/></form>
<?php if (!is_null($deleted_count)) : ?>
<div style="margin-top:20px;">
✅ Total deleted <strong><?php echo $deleted_count; ?></strong> Individual commodities.
</div>
<?php endif; ?>
</div>
<?php
}