How to automatically delete featured image when deleting post - Wordpress

0 votes
asked Nov 7 by katib (115 points)

Recently while optimization my wordpress site i have accross some images that were set featured when the post was created. There are lot of orphan images wondering around. How i can get rid of them ?

1 Answer

0 votes
answered Nov 7 by ubuntu (106 points)

You can manually remove all your images for now, but moving forward add this to your function file.

add_action( 'before_delete_post', 'wps_remove_attachment_with_post', 10 );
function wps_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);

*disclaimer : I have't tested the code but it should work.