Find out in this tutorial how to delete the featured image when deleting any type of WordPress post or entry using code.
The other day a subscriber wanted to know if there was a way to delete the featured images of products that are deleted.
In this case, there is quite a lot of product turnover and many of them are not coming back to her ecommerce. To avoid an unnecessary accumulation of images that will no longer be used, an interesting strategy is to delete them together with the product.
In addition to this case, many others can be applied. Are you interested?
Let’s see how you can achieve this.
Snippet to delete the featured image when deleting a WordPress post
Add the following code at the end of functions.php or in your functionality plugin:
In this code you use the
before_delete_post hook to add the task to delete the featured image just before deleting the post.
Note that the image will be deleted when you delete the post from the trash, not when you send it to the trash.
Warning: I only recommend using this snippet if you know that the featured image is not being used elsewhere on the site.
If you only want it to apply to a specific type of post you can do so using the following snippet:
In this case only the featured images of the products will be removed.
To adjust it to your needs just change ‘product’ for the name of the Custom Post Type you are interested in.
Now you know how to delete featured images when deleting any WordPress post type.
Any questions? Let me know in the comments.
And if you want to give me any suggestion for future tutorials, leave it in the contact form. Advantages of being a subscriber. 😉