Skip to content

Instantly share code, notes, and snippets.

@sabrina-zeidan
Last active October 22, 2022 14:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sabrina-zeidan/1bded84f77c71fbea289a691ae4e56c0 to your computer and use it in GitHub Desktop.
Save sabrina-zeidan/1bded84f77c71fbea289a691ae4e56c0 to your computer and use it in GitHub Desktop.
Delete all attachments attached to specified custom posts (card in this case) [Wordpress]
function delete_cpt_attachments(){
$attachments = get_posts( array(
'post_type' => 'attachment',
'numberposts' =>-1,
));
if ($attachments) {
foreach ($attachments as $attachment){
$parent_id = $attachment->post_parent;
if ( 'card' == get_post_type($parent_id) ) {
$attachmentID = $attachment->ID;
$attachment_path = get_attached_file( $attachmentID);
//Delete attachment from database only, not file
$delete_attachment = wp_delete_attachment($attachmentID, true);
//Delete attachment file from disk
$delete_file = unlink($attachment_path);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment