Using WordPress ‘after_delete_post’ PHP action

The after_delete_post WordPress action fires after a post is deleted using the wp_delete_post() function.

Usage

add_action('after_delete_post', 'your_custom_function', 10, 2);

function your_custom_function($postid, $post) {
    // Your custom code here
}

Parameters

  • $postid: (int) The ID of the deleted post.
  • $post: (WP_Post) The deleted post object.

More information

See WordPress Developer Resources: after_delete_post

Examples

Log deleted posts

Log the title and ID of deleted posts in a separate log file.

add_action('after_delete_post', 'log_deleted_posts', 10, 2);

function log_deleted_posts($postid, $post) {
    // Get the post title
    $post_title = $post->post_title;

    // Prepare log message
    $log_message = "Post ID: {$postid}, Post Title: {$post_title} was deleted.\n";

    // Write the message to the log file
    file_put_contents('deleted_posts.log', $log_message, FILE_APPEND);
}

Delete associated metadata

Delete custom metadata when a post is deleted.

add_action('after_delete_post', 'delete_custom_metadata', 10, 2);

function delete_custom_metadata($postid, $post) {
    // Delete custom metadata
    delete_post_meta($postid, 'your_custom_meta_key');
}

Notify admin of deleted posts

Send an email to the admin when a post is deleted.

add_action('after_delete_post', 'notify_admin_on_post_delete', 10, 2);

function notify_admin_on_post_delete($postid, $post) {
    // Prepare email subject and message
    $subject = "A post has been deleted";
    $message = "The post with ID: {$postid} and title: '{$post->post_title}' has been deleted.";

    // Send email to the admin
    wp_mail(get_bloginfo('admin_email'), $subject, $message);
}

Unschedule future events

Unschedule a future event related to the deleted post using the post ID.

add_action('after_delete_post', 'unschedule_future_event', 10, 2);

function unschedule_future_event($postid, $post) {
    // Unschedule the event related to the post
    wp_clear_scheduled_hook('your_scheduled_hook', array($postid));
}

Update a custom counter

Decrease a custom counter when a post is deleted.

add_action('after_delete_post', 'update_custom_counter', 10, 2);

function update_custom_counter($postid, $post) {
    // Get the current counter value
    $counter = get_option('your_custom_counter', 0);

    // Decrease the counter value by 1
    $counter--;

    // Update the counter value in the database
    update_option('your_custom_counter', $counter);
}