How to automatic remove featured image when deleting the post

When you need autoremove featured image from the post – when the post will be deleted, please add code:

<?php 
add_action( 'before_delete_post', 'arkadiuszbartnik_remove_attachment_with_post', 10 );
function arkadiuszbartnik_remove_attachment_with_post($post_id)
{
        if(has_post_thumbnail( $post_id ))
        {
          $attachment_id = get_post_thumbnail_id( $post_id );
          wp_delete_attachment($attachment_id, true);
        }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *