The following script deletes all images, except those that are in use by WooCommerce products.
function delete_unused_images() {
// Get all product IDs
$product_ids = wc_get_products(array('limit' => -1, 'return' => 'ids'));
// Get all attachment IDs
$attachments = get_posts(array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => 'inherit',
));
// Create an array to hold IDs of product images
$product_image_ids = array();
// Loop through each product to get their featured images
foreach ($product_ids as $product_id) {
$product_image_ids[] = get_post_thumbnail_id($product_id);
}
// Loop through each attachment and delete if not a product image
foreach ($attachments as $attachment) {
if (!in_array($attachment->ID, $product_image_ids)) {
wp_delete_attachment($attachment->ID, true);
}
}
}
// Hook the function to an action, e.g., admin_init
add_action('admin_init', 'delete_unused_images');
Code language: PHP (php)
Source: Einar