How to hook a function only when I need to delete permanently a post?

I need to hook a function only when I delete permanently a post from the database, I’ve tried the ‘before_delete_post’ hook, however, it’s called both when it’s trashed and permanently deleted.

The wp_delete_post() function calls wp_trash_post() and should stop processing, but it looks like the wp_delete_post() is called again after the post is trashed.

Read More

I’ve seen this question: WordPress Delete hook with wp_delete_post function?. My need is exactly the oposite of it.

Related posts

Leave a Reply

2 comments

  1. before_delete_post is not called when a post is only trashed.

    While wp_delete_post() can trash posts (if the post is not trashed and its not being forcibly deleted): it does so by calling wp_trash_post() and exiting the function prior to the triggering the action before_delete_post.

    I’ve tested this, the following function will only ‘die’ when you permanently delete a post, but not when its confined to the trash. The wp_die is to demonstrate when the call is being made – I do not recommend using it on a live site.

    add_action('before_delete_post', 'my_deleted_post');
    function my_deleted_post($post_id){
       wp_die(var_dump($post_id));
    };
    

    The wp_delete_post() function can be found here (WP 3.3.1)

  2. The issue was the “Sitewide tags” plugin which was misbehaving the natural WP flow. A function called sitewide_tags_post_delete() is hooked on ‘trash_post’ and it’s calling wp_delete_post() to delete the post on the main blog.

    Following the @Stephen’s approach, I did this:

    add_action('before_delete_post', 'my_deleted_post');
    function my_deleted_post($post_id){
      global $blog_id;   
      if($blog_id == <main_blog_id>){ // usually is 1
        return false;
      }
    
      //do whatever you need :)
    };