Created
November 6, 2023 14:04
-
-
Save Qubadi/e6da6e619fb7516fa902a27e26d68a7f to your computer and use it in GitHub Desktop.
When a product is deleted, this code will work to remove the featured image and gallery images of a WooCommerce product from the WordPress media library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_action('before_delete_post', function ($post_id) { | |
// Check if the post being deleted is a WooCommerce product | |
if (get_post_type($post_id) !== 'product') { | |
return; | |
} | |
// Delete the featured image (post thumbnail) if it exists | |
$thumbnail_id = get_post_thumbnail_id($post_id); | |
if (!empty($thumbnail_id)) { | |
wp_delete_attachment($thumbnail_id, true); | |
} | |
// Get the gallery image IDs and delete them if they exist | |
$gallery_images = get_post_meta($post_id, '_product_image_gallery', true); | |
if (!empty($gallery_images)) { | |
// The gallery image IDs are separated by commas, so we explode them into an array | |
$image_ids = explode(',', $gallery_images); | |
foreach ($image_ids as $image_id) { | |
// Convert each ID to an integer and delete the attachment | |
$image_id = intval($image_id); | |
if ($image_id) { | |
wp_delete_attachment($image_id, true); | |
} | |
} | |
} | |
}, 10, 1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment