Last active
December 1, 2017 01:25
-
-
Save majick777/4201f64e8355d0f239c37efa0bb570d3 to your computer and use it in GitHub Desktop.
Function to Delete All Attachments for a Post
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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