before_delete_post

Home » Hooks » before_delete_post

The "before_delete_post" hook in WordPress is a powerful tool that allows developers to execute custom code just before a post is permanently deleted from the database. This hook is triggered right before the post deletion process begins, giving you the ability to perform any necessary actions or modifications.

The "before_delete_post" hook is commonly used for tasks such as logging or creating backups before a post is deleted, updating related data or metadata, or even preventing the deletion of a post under certain conditions.

To utilize the "before_delete_post" hook, you need to register a callback function that will be executed when the hook is triggered. Here’s an example usage code that demonstrates how to leverage this hook:

function my_custom_before_delete_post_callback($post_id) {
    // Perform custom actions before post deletion
    // Example: create a backup of the post data
    $backup = get_post($post_id);
    // ... additional code

    // Optionally, you can prevent the post deletion by returning false
    // Example: prevent deletion if the post is published
    if (get_post_status($post_id) === 'publish') {
        return false;
    }

    // Return true to allow the post deletion to proceed
    return true;
}
add_action('before_delete_post', 'my_custom_before_delete_post_callback');

In this example, the "my_custom_before_delete_post_callback" function is registered as the callback function for the "before_delete_post" hook. Inside the function, you can add your custom code to perform actions before the post is deleted. You can also choose to prevent the deletion by returning false based on specific conditions.

By utilizing the "before_delete_post" hook, you have fine-grained control over the post deletion process and the ability to customize it to meet your specific needs.

Learn More on WordPress.org

WordPress snippets using the before_delete_post hook

Register an account to save your snippets or go Pro to get more features.