WordPress.org

Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Plugin API/Action Reference/delete post

Description

delete_post is fired before and after a post (or page) is deleted from the database.

However by this time the post comments and metadata have been already deleted. Use the before_delete_post hook to catch post deletion before that.

Definitions

/wp-includes/post.php - pre-deletion
(#2041) (integer) The $postid parameter is the same value that was passed to wp_delete_post().
Hook: do_action( 'delete_post', $postid );
/wp-includes/post.php - post-deletion
(#2043) (integer) The $postid parameter is the same value that was passed to wp_delete_post().
Hook: do_action( 'deleted_post', $postid );

Example

Let's suppose you have a plugin that, for one reason or another, stores its own post metadata in a separate database table called codex_postmeta. One of the ways you can achieve synchronisation is to be made aware when a post is deleted so that you can replicate the changes yourself.

<?php
add_action
'admin_init''codex_init' );
function 
codex_init() {
    
add_action'delete_post''codex_sync'10 );
}

function 
codex_sync$pid ) {
    global 
$wpdb;
    if ( 
$wpdb->get_var$wpdb->prepare'SELECT post_id FROM codex_postmeta WHERE post_id = %d'$pid ) ) ) {
        
$wpdb->query$wpdb->prepare'DELETE FROM codex_postmeta WHERE post_id = %d'$pid ) );
    }
}
?>

Related

wp_delete_post() before_delete_post()