Last active
October 22, 2022 14:13
-
-
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]
This file contains 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
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