Alternatex
Alternatex

Reputation: 1552

WordPress delete_post hook calls function twice

Here is how I've implemented it:

add_action( 'delete_post', array( 'MyClassName', 'delete' ) );

In the delete function I was using a $wpdb->insert command to see whether the function gets called. But I see that the $wpdb->insert command is called twice (inserts two rows in my table). Any ideas as to why something like this might happen?

I've also attempted to use the before_delete_post hook since it doesn't really make a difference to me but I get the same outcome.

EDIT:

It seems as though the delete function is called for each entry in the wp_posts table for some reason. So if the post has 3 revisions, the delete function will be called 4 times (the original post + 3 revisions). This is really weird behavior.

Upvotes: 0

Views: 235

Answers (1)

Alternatex
Alternatex

Reputation: 1552

I found my solution.

The function you hook into delete_post (or probably any other similar hook) executes as many times as needed. Considering delete_post needs to delete the post and all of its revisions, it will always run more than once. In order to avoid having your function execute each time WordPress deletes a record from the database you can use did_action( $hook ). This function returns the number of times the hook executed. With this in consideration, we can fix our multiple-executions problem by placing this condition into our function:

if (did_action('delete_post') === 1)
{
    // execute code here
}

Upvotes: 0

Related Questions