Wordpress - Delete Associated Media Upon Page Deletion
I suppose you're looking for something like this...?
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');
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' );