raunak-gupta
10/27/2016 - 1:48 PM

WordPress delete media on post/page/product deletion

WordPress delete media on post/page/product deletion

<?php

function delete_associated_media($id) {
    
    $media = get_children(array(
        'post_type' => 'attachment',
        'post_parent' => $id,
        'post_status' => 'inherit',
        //'post_mime_type' => 'image/jpeg',
        'numberposts' => -1
    ));
    
    if (empty($media)) return;

    foreach ($media as $file) {
        //deletes an attachment and all of its derivatives. 
        if ( false === wp_delete_attachment($file->ID, TRUE) ) { //force deletion (so no trash)
            // Log failure to delete attachment.
        }
    }
}
add_action('before_delete_post', 'delete_associated_media');