Delete Associated Media Upon Page Deletion

How about this? It adapts an example on the get_posts() function reference page.

function delete_post_media( $post_id ) {

    $attachments = get_posts( array(
        'post_type'      => 'attachment',
        'posts_per_page' => -1,
        'post_status'    => 'any',
        'post_parent'    => $post_id
    ) );

    foreach ( $attachments as $attachment ) {
        if ( false === wp_delete_attachment( $attachment->ID ) ) {
            // Log failure to delete attachment.
        }
    }
}

add_action( 'before_delete_post', 'delete_post_media' );

Leave a Comment