Delete Custom Posts & Attachments

admin2025-06-04  12

I'm trying to setup a script that will automatically delete all posts of a custom post type, including their attachments. The first part of the script seems to work fine:

    $allposts= get_posts( array('post_type'=>'wpbb_application','numberposts'=>-1) );
foreach ($allposts as $eachpost) {
  wp_delete_post( $eachpost->ID, true );
}

This checks for all posts of the 'wpbb_application' CPT, and then deletes them. It works fine as far as I can tell, but it leaves the PDFs that are attached to the posts in the media library. What I would like to do is automatically remove these attachments too. I therefore added this to precede the code:

add_action( 'before_delete_post', function( $id ) {
  $attachments = get_attached_media( 'application', $id );
  foreach ($attachments as $attachment) {
    wp_delete_attachment( $attachment->ID, 'true' );
  }
} );

I can't seem to get that to work for some reason. Can anyone shed any light on this?

Thanks.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749038285a315830.html

最新回复(0)