钩子文档

delete_post

💡 云策文档标注

概述

delete_post 是一个 WordPress 动作钩子,在文章从数据库删除前立即触发。开发者可利用此钩子在文章删除时执行自定义操作,如清理相关数据。

关键要点

  • 触发时机:在文章从数据库删除前立即触发,但注意此时文章评论和元数据可能已被删除。
  • 参数:$post_id(整数,文章ID)和 $post(WP_Post 对象,文章对象)。
  • 替代钩子:如需在文章删除前更早阶段捕获,可使用 before_delete_post 钩子。
  • 版本变更:WordPress 5.5.0 版本添加了 $post 参数。

代码示例

add_action( 'admin_init', 'wpdocs_codex_init' );
function wpdocs_codex_init() {
    add_action( 'delete_post', 'wpdocs_codex_sync', 10 );
}

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

注意事项

此钩子触发时,文章评论和元数据可能已被删除,开发者应确保同步逻辑考虑此点,避免数据不一致。


📄 原文内容

Fires immediately before a post is deleted from the database.

Parameters

$post_idint
Post ID.
$postWP_Post
Post object.

More Information

Take note, by the time the hook triggers, the post comments and metadata would have already been deleted. Use the before_delete_post hook to catch post deletion before that.

Source

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

Changelog

Version Description
5.5.0 Added the $post parameter.
1.2.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    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 synchronization is to be made aware when a post is deleted so that you can replicate the changes yourself.

    add_action( 'admin_init', 'wpdocs_codex_init' );
    function wpdocs_codex_init() {
        add_action( 'delete_post', 'wpdocs_codex_sync', 10 );
    }
    
    function wpdocs_codex_sync( $pid ) {
        global $wpdb;
        $query = $wpdb->prepare( 'SELECT post_id FROM codex_postmeta WHERE post_id = %d', $pid );
        $var = $wpdb->get_var( $query );
        if ( $var ) {
            $query2 = $wpdb->prepare( 'DELETE FROM codex_postmeta WHERE post_id = %d', $pid );
            $wpdb->query( $query2 );
        }
    }