Search code examples
wordpressdelete-row

Wordpress - action when post is deleted (more then one)


I'm having problem with triggering function on "delete_post" action. I'm building functionality where i had to add one more table in database (i cannot use wp_postmeta for this one). Because of this I created a custom table which have that additional data related with posts. I would like that, when admin delete post from admin panel, to delete data for that post in my custom table (i don't want redundant data to stay there when post is gone)

And i implemented something like this:

add_action('admin_init', 'codex_init');
function codex_init() {
   if (current_user_can('delete_posts')) add_action('delete_post', 'delete_something');
}

function delete_something($postid) {
   //here im deleting everything from that table with that post id for that post type
}

And this works perfect if someone click to delete only one post. But when I want to delete more posts at once (checking buttons on wordpress admin menu and selecting delete option - bulk deletion), this will not work? Am i doing something wrong here, or is there different action when someone want to delete several posts at once?


EDIT:

As indicated in the comment bellow, this action works perfectly for bulk and individual delete actions as well. My issue was related with the usage of the global $post variable - to get the id of individual posts - when instead I should use parameter which is provided to the function directly.


Solution

  • I looked at the code in wp-admin/edit.php it does trigger the function wp_delete_post which has your action.
    Try this. Does it die and hit the var_dump?

    add_action('admin_init', 'codex_init');
    function codex_init() {
       if (current_user_can('delete_posts')) add_action('delete_post', 'delete_something');
    }
    
    function delete_something($postid) {
         var_dump('trigger'.$postid);die();
         //here im deleting everything from that table with that post id for that post type
    }