I am using wp_delete_post function to delete the selected posts shown on the front-end (in my theme page). Posts are being deleted successfully.

// delete all selected posts
foreach( $_POST['list_id'] as $listID ) {
   if( wp_delete_post( $listID ) ) {
      echo 'hi';

In my function.php file i added the following hook for the delete_post.

// Delete Post Attachment
function abc_delete_attachment($post_id) {
    $args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null,
                    'post_parent' => $post_id ); 
    $attachments = get_posts($args);
    if ($attachments) {
        foreach ( $attachments as $attachment ) {
           if( wp_delete_attachment( $attachment->ID,true ) ) {
              // Just to check if the hook is called or not i used wp_redirect 

But for some reason, this action is not being called. and the attachments are not being deleted permanently rather they are left unattached (the default behavior).

Can anyone help me out?


You need to use before_delete_post action. As its already very late when delete_post action is run. Wordpress un-attach all the attachments before running delete_post action. So when you run get_posts in your delete_attachment function there are no attachments found.

So you need to hook your function to before_delete_post.

  • I was testing before_delete_post hook when you replied. Thanks for confirming the solution :P – booota Sep 19 '11 at 10:32
  • Glad that you were able to figure it out your self. :) – Hameedullah Khan Sep 19 '11 at 10:53
  • With delete_post action $attachments will be just empty array – Mamaduka Sep 19 '11 at 10:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.