The before_delete_post WordPress PHP action fires before a post is deleted, at the start of wp_delete_post()
.
Usage
add_action('before_delete_post', 'your_function_name', 10, 2); function your_function_name($postid, $post) { // your custom code here }
Parameters
- $postid (int): The ID of the post being deleted.
- $post (WP_Post): The post object representing the post being deleted.
More information
See WordPress Developer Resources: before_delete_post
Examples
Log post deletion
Log the title of a post before it is deleted.
add_action('before_delete_post', 'log_post_deletion', 10, 2); function log_post_deletion($postid, $post) { error_log('Deleting post: ' . $post->post_title); }
Prevent post deletion based on a custom field
Prevent deletion of posts with a specific custom field value.
add_action('before_delete_post', 'prevent_post_deletion', 10, 2); function prevent_post_deletion($postid, $post) { $prevent_delete = get_post_meta($postid, 'prevent_delete', true); if ($prevent_delete == 'yes') { wp_die('This post cannot be deleted.'); } }
Delete associated attachments
Delete all associated attachments when a post is deleted.
add_action('before_delete_post', 'delete_associated_attachments', 10, 2); function delete_associated_attachments($postid, $post) { $attachments = get_attached_media('image', $postid); foreach ($attachments as $attachment) { wp_delete_attachment($attachment->ID, true); } }
Send an email notification
Send an email notification to the site admin when a post is deleted.
add_action('before_delete_post', 'send_email_on_post_deletion', 10, 2); function send_email_on_post_deletion($postid, $post) { $admin_email = get_option('admin_email'); $subject = 'A post was deleted'; $message = 'Post "' . $post->post_title . '" was deleted.'; wp_mail($admin_email, $subject, $message); }
Update the post count of an author
Update the total post count of an author when a post is deleted.
add_action('before_delete_post', 'update_author_post_count', 10, 2); function update_author_post_count($postid, $post) { $author_id = $post->post_author; $post_count = get_user_meta($author_id, 'total_posts', true); update_user_meta($author_id, 'total_posts', $post_count - 1); }