钩子文档

delete_attachment

💡 云策文档标注

概述

delete_attachment 是一个 WordPress 动作钩子,在 wp_delete_attachment() 函数开始时触发,用于在附件删除前执行自定义操作。自 WordPress 2.8 起,该钩子在删除数据库和文件系统内容之前触发,增强了实用性。

关键要点

  • 触发时机:在 wp_delete_attachment() 函数开始时,附件被删除之前触发。
  • 参数:$post_id(附件 ID)和 $post(WP_Post 对象),后者在 WordPress 5.5.0 版本中添加。
  • 历史变化:WordPress 2.8 之前,该钩子在附件删除后触发,之后改为删除前触发,提高了可用性。
  • 相关函数:与 wp_delete_attachment() 函数关联,用于处理附件的删除或移至回收站。

代码示例

function wpdocs_delete_attachment( $post_id ) {
    // Do something before attachment deleted

    // get attached file dir
    $file = get_attached_file( $post_id );

    // get file name of attachment to be deleted
    $file_name = wp_basename( $file );
}
add_action( 'delete_attachment', 'wpdocs_delete_attachment' );

📄 原文内容

Fires before an attachment is deleted, at the start of wp_delete_attachment() .

Parameters

$post_idint
Attachment ID.
$postWP_Post
Post object.

More Information

Up to and including WordPress 2.7, it is fired ”after” the attachment is deleted from the database and the file system, limiting its usefulness. As of changeset #10400 (WordPress 2.8), the action will fire ”before” anything is deleted.

Source

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

Changelog

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

User Contributed Notes

  1. Skip to note 2 content

    Below is the basic example how delete_attachment action works.

    function wpdocs_delete_attachment( $post_id ) {
    	// Do something before attachment deleted
    
    	// get attached file dir
    	$file = get_attached_file( $post_id );
    
    	// get file name of attachment to be deleted
    	$file_name = wp_basename( $file );
    }
    add_action( 'delete_attachment', 'wpdocs_delete_attachment' );