Step 1: Create a Custom Function
Add a custom function to your theme’s functions.php
file or a custom plugin that drafts all products in a specific category.
function draft_products_in_category($category_slug) {
// Get the category by slug
$category = get_term_by('slug', $category_slug, 'product_cat');
if (!$category) {
return 'Category not found.';
}
// Get all products in the category
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $category_slug,
),
),
);
$products = new WP_Query($args);
// Loop through products and set them to draft
if ($products->have_posts()) {
while ($products->have_posts()) {
$products->the_post();
$product_id = get_the_ID();
$product = wc_get_product($product_id);
$product->set_status('draft');
$product->save();
}
wp_reset_postdata();
}
return 'All products in the category have been set to draft.';
}
Step 2: Create a Custom Admin Page (Optional)
For a user-friendly approach, create a custom admin page where you can run this function by selecting a category from a dropdown.
// Add menu item
function add_custom_admin_menu() {
add_submenu_page(
'woocommerce',
'Draft Products by Category',
'Draft Products',
'manage_options',
'draft-products-category',
'draft_products_category_page'
);
}
add_action('admin_menu', 'add_custom_admin_menu');
// Display the admin page
function draft_products_category_page() {
?>
<div class="wrap">
<h1>Draft Products by Category</h1>
<form method="post" action="">
<label for="category">Select Category:</label>
<select name="category" id="category">
<?php
$categories = get_terms(array('taxonomy' => 'product_cat', 'hide_empty' => false));
foreach ($categories as $category) {
echo '<option value="' . esc_attr($category->slug) . '">' . esc_html($category->name) . '</option>';
}
?>
</select>
<input type="submit" name="draft_products" value="Draft Products" class="button button-primary">
</form>
<?php
if (isset($_POST['draft_products'])) {
$category_slug = sanitize_text_field($_POST['category']);
$result = draft_products_in_category($category_slug);
echo '<p>' . esc_html($result) . '</p>';
}
?>
</div>
<?php
}