Created
November 6, 2023 08:46
-
-
Save Qubadi/6bb6b76e070d96c5076da748b0e5b872 to your computer and use it in GitHub Desktop.
Jetengine WordPress post or custom post type when the post is permanently deleted. It also includes functionality to handle meta fields for galleries, ensuring that all related images are thoroughly deleted.
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) { | |
// If you want to restrict this to just the 'cpt slug' post type, uncomment the following line: | |
// if (get_post_type($post_id) !== 'ADD YOUR CPT SLUG') return; | |
// Delete the featured image (post thumbnail). | |
$thumbnail_id = get_post_thumbnail_id($post_id); | |
if ($thumbnail_id) { | |
wp_delete_attachment($thumbnail_id, true); | |
} | |
// Handle the deletion of gallery images stored in the 'gallery' custom field. | |
$gallery_images = get_post_meta($post_id, 'ADD YOUR META FIELD GALLERY', true); | |
// Check if gallery images are stored as a string of IDs separated by commas. | |
if ($gallery_images) { | |
// Convert the string to an array of IDs. | |
$image_ids = explode(',', $gallery_images); | |
// Loop through each ID and delete the attachment. | |
foreach ($image_ids as $image_id) { | |
// Ensure that the ID is an integer. | |
$image_id = intval($image_id); | |
if ($image_id) { | |
wp_delete_attachment($image_id, true); | |
} | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment