0

I found a solution of removing featured image related to the post when delete the post from this article but, I want to remove all the uploaded media also with post removing. Delete all WP image gallery (included generated thumbnails) that are attached to a post. How can I do this?

1

1 Answer 1

2

You can try using the function get_attached_media() like this:

add_action( 'before_delete_post', 'wps_remove_attachment_with_post', 10 );
function wps_remove_attachment_with_post( $post_id ) {

    /** @var WP_Post[] $images */
    $images = get_attached_media( 'image', $post_id );

    foreach ( $images as $image ) {
        wp_delete_attachment( $image->ID, true );
    }
}

Note that this will permanently delete all the image files related to this post. If those attachments are used somewhere else as well, those links will be broken.

1
  • Great thanks for this help Apr 10, 2019 at 14:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.