• I am building my mother-in-law a site for her business. She is NOT tech savy. I’m afraid over time she is going to fill up her web server with images as she creates posts and deletes them. I found a function that is supposed to delete images that are associated with a particular post when the post is deleted. I’m just not sure where to put it and if it’s going to be a wise idea… Here is the code:

    function delete_associated_media($id) {
        // check if page
        if ('page' !== get_post_type($id)) return;
    
        $media = get_children(array(
            'post_parent' => $id,
            'post_type' => 'attachment'
        ));
        if (empty($media)) return;
    
        foreach ($media as $file) {
            // pick what you want to do
            wp_delete_attachment($file->ID);
            unlink(get_attached_file($file->ID));
        }
    }
    add_action('before_delete_post', 'delete_associated_media');

    If anyone can help, that would be awesome!
    PS – I am using a custom post type – portfolio

  • The topic ‘Delete Images Associated with Post when the post is moved to trash’ is closed to new replies.