The deleted_post WordPress action fires immediately after a post is deleted from the database.
Usage
add_action('deleted_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 deleted post.
More information
See WordPress Developer Resources: deleted_post
Examples
Log deleted posts
Log information about deleted posts to a custom log file.
add_action('deleted_post', 'log_deleted_posts', 10, 2); function log_deleted_posts($postid, $post) { // Get the post type and date $post_type = $post->post_type; $post_date = $post->post_date; // Format the log entry $log_entry = "Deleted post: {$postid}, Type: {$post_type}, Date: {$post_date}" . PHP_EOL; // Append the log entry to the log file file_put_contents('deleted_posts.log', $log_entry, FILE_APPEND); }
Update post count
Update a custom meta value that keeps track of the total number of published posts for a user.
add_action('deleted_post', 'update_user_post_count', 10, 2); function update_user_post_count($postid, $post) { // Check if the post was published if ($post->post_status === 'publish') { $author_id = $post->post_author; $post_count = get_user_meta($author_id, 'published_post_count', true); update_user_meta($author_id, 'published_post_count', --$post_count); } }
Notify admin of deleted posts
Send an email to the admin when a post is deleted.
add_action('deleted_post', 'notify_admin_of_deleted_post', 10, 2); function notify_admin_of_deleted_post($postid, $post) { $post_title = $post->post_title; $admin_email = get_option('admin_email'); wp_mail($admin_email, 'Post Deleted', "The post '{$post_title}' (ID: {$postid}) has been deleted."); }
Remove post from custom cache
Remove the post from a custom caching system when it’s deleted.
add_action('deleted_post', 'remove_post_from_cache', 10, 2); function remove_post_from_cache($postid, $post) { // Assume $cache is your custom caching object $cache_key = "post_{$postid}"; $cache->delete($cache_key); }
Delete post-related custom data
Delete custom data related to the post from another table in the database.
add_action('deleted_post', 'delete_post_related_data', 10, 2); function delete_post_related_data($postid, $post) { global $wpdb; $table_name = $wpdb->prefix . 'custom_data'; $wpdb->delete($table_name, array('post_id' => $postid)); }