Skip to content

Instantly share code, notes, and snippets.

@majick777
Last active December 1, 2017 01:25
Show Gist options
  • Save majick777/4201f64e8355d0f239c37efa0bb570d3 to your computer and use it in GitHub Desktop.
Save majick777/4201f64e8355d0f239c37efa0bb570d3 to your computer and use it in GitHub Desktop.
Function to Delete All Attachments for a Post
// Delete All Attachments for a Specified Post
// -------------------------------------------
function wp_delete_post_attachments($post, $deletethumbnail = false);
if (!is_object( $post )) {$post = get_post( $post );}
$uploads = wp_upload_dir();
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => 'any',
'post_parent' => $post->ID,
);
if ( $deletethumbnail ) {
$args['exclude'] => get_post_thumbnail_id( $post->ID );
}
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$data = wp_get_attachment_metadata( $attachment->ID );
unlink( $uploads['basedir'] . '/' . $data['file'] );
foreach ( $data['sizes'] as $size ) {
unlink( $uploads['basedir'] . '/' . $size['file'] );
}
wp_delete_post( $attachment->ID );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment