钩子文档

before_delete_post

💡 云策文档标注

概述

before_delete_post 是一个 WordPress 动作钩子,在 wp_delete_post() 函数开始时触发,用于在文章被删除前执行自定义操作。它适用于文章永久删除场景,但不适用于文章移至回收站或附件删除。

关键要点

  • 触发时机:在 wp_delete_post() 开始时,文章关联数据(如元数据)被删除之前。
  • 参数:$post_id(整数,文章ID)和 $post(WP_Post 对象,文章对象)。
  • 适用场景:文章永久删除(包括回收站禁用时的强制删除),不适用于文章移至回收站(使用 wp_trash_post)或附件删除(使用 delete_attachment)。
  • 执行顺序:before_delete_post 触发后,关联数据被删除,接着 delete_post 动作执行,文章从数据库移除,最后 deleted_post 动作执行。
  • 版本历史:WordPress 3.2.0 引入,5.5.0 添加 $post 参数。

代码示例

add_action( 'before_delete_post', 'my_custom_before_delete', 10, 2 );
function my_custom_before_delete( $post_id, $post ) {
    if ( 'my_custom_post_type' !== $post->post_type ) {
        return;
    }
    // 在此处执行自定义删除操作
}

注意事项

  • 避免使用全局变量,优先使用钩子参数(如 $post_id 和 $post),以提高代码的稳定性和兼容性。
  • 确保钩子逻辑仅针对特定文章类型,避免影响其他文章类型。

📄 原文内容

Fires before a post is deleted, at the start of wp_delete_post() .

Description

See also

Parameters

$post_idint
Post ID.
$postWP_Post
Post object.

More Information

This hook runs:

  • Just before other data associated with the post is deleted – like meta data. After the other data is deleted, the delete_post action executes, the primary post is removed, and then the deleted_post action is executed.
  • When items marked for trash are going through final (forced) deletion (e.g. the trash is disabled and an item is deleted).

This hook does not run:

  • For posts that are being marked as trash (unforced). The wp_trash_post hook is the functional equivalent, executed just before items are marked as trash.
  • For attachments. The delete_attachment hook is the functional equivalent, executed just before posts of type attachment are processed. With attachments, exactly as with other post types, meta data is removed, the delete_post action is run, then the attachment is removed from the database, and finally, the deleted_post action is run.

Source

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

Changelog

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

User Contributed Notes

  1. Skip to note 4 content

    Let’s suppose you have a plugin and when a certain post_type is deleted you want to perform some action.