add_action not using ‘delete_post’ action with wp_delete_post

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 
                  wp_redirect(site_url());
           }
        }
    }
}
add_action('delete_post','abc_delete_attachment');

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?

1 Answer
1

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.

add_action('before_delete_post','abc_delete_attachment');

Leave a Comment