Can I differentiate between “Delete Post Permanently” and “Empty Trash” and do something for each accordingly?

I’m currently working on developing a plugin with a custom post type of “Dealer Location”. (Not relevant to question, just a bit of background)

When a post is in the trash and “delete permanently” is pressed, I need to remove this piece of meta from each user.

When a post/posts are in the trash and “empty trash” is pressed, I need to run through EACH location being deleted and do something.

I have an extremely basic function just to test when it runs right now, as I have all the other nuts & bolts (removing user meta, etc) figured out..:

public function wcmdl_remove_deleted_location_users(){

    die;
} 

And the action I’m using is..:

$this->loader->add_action('before_delete_post', $plugin_admin, 'wcmdl_remove_deleted_location_meta');

I’ve tried using the hook ‘delete_post’ too and in both cases the function fires when expected. However, it fires on BOTH “delete permanently” AND “empty trash”.

Is there any sort of hook or if statement I can use to differentiate between mass-deleting and single-deleting in this instance? If not, would it be viable to pass some value via ajax/js depending on which button is pressed, and use it to determine the action taken in a function via an if/else statement?

1 Answer
1

So as leymannx pointed out in his comment, the “delete_post” hook actually handles both scenarios I was looking for, as it seems to know to run a “for each post deleted, do x” when “Empty Trash” is clicked and will also “do x” when “Delete Post Permanently” is clicked!

My final code ended up looking something like..:

    public function wcmdl_remove_deleted_location_users(){

      $currentpost    = get_the_ID();
      $parentid       = wp_get_post_parent_id( $currentpost );

      if( get_post_type() == 'dealer_location' ) {
        //do stuff involving $currentpost and $parentid here...
      }
    }

Keeping in mind that this is being used within a standard plugin boilerplate format and NOT directly in the functions.php file of a child theme, this hook was placed in the “includes>class-[plugin name].php” file..:

        $this->loader->add_action('delete_post', $plugin_admin, 'wcmdl_remove_deleted_location_users');

If you were to be trying to do the same via your functions.php, the structure for this would instead be:

add_action('delete_post', 'wcmdl_remove_deleted_location_users');

Leave a Comment