do_action( ‘after_delete_post’, int $post_id, WP_Post $post )

Fires after a post is deleted, at the conclusion of wp_delete_post() .

Description

See also

Parameters

$post_idint
Post ID.
$postWP_Post
Post object.

Source

do_action( 'after_delete_post', $post_id, $post ); 

Changelog

VersionDescription
5.5.0Added the $post parameter.
3.2.0Introduced.

User Contributed Notes

  1. Skip to note 4 content

    Performing Actions After Deleting a Post Based on Multiple Conditions

    In this tutorial, you will learn how to execute custom code after a WordPress post is deleted, but only under specific conditions. We will use a combination of post type, post status, and custom field value checks to determine whether to run the custom code.

    Step 1: Hook into the after_delete_post Action

    First, we need to hook into the after_delete_post action, which fires after a post is deleted. Add the following code to your theme’s functions.php file or your custom plugin file:

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

    Step 2: Define the wpdocs_do_something Function

    function wpdocs_do_something( $post_id, $post ) { // Condition 1: Check for specific post types $allowed_post_types = array( 'books', 'movies', 'products' ); if ( ! in_array( $post->post_type, $allowed_post_types ) ) { return; } // Condition 2: Check for specific post statuses (e.g., only if the post was published) $allowed_post_statuses = array( 'publish', 'private' ); if ( ! in_array( get_post_status( $post_id ), $allowed_post_statuses ) ) { return; } // Condition 3: Check for a specific custom field value $custom_field_value = get_post_meta( $post_id, 'wpdocs_field_key', true ); if ( 'specific_value' !== $custom_field_value ) { return; } // Write your code here. All conditions met // Example: Log the deletion error_log( 'Post with ID ' . $post_id . ' and type ' . $post->post_type . ' has been deleted.' ); // Add your custom code here // Example: Remove related data from a custom table global $wpdb; $wpdb->delete( $wpdb->prefix . 'custom_table', array( 'post_id' => $post_id ) ); }

You must log in before being able to contribute a note or feedback.