钩子文档

wp_delete_file

💡 云策文档标注

概述

wp_delete_file 是一个 WordPress 过滤器,用于在删除文件时过滤文件路径。它允许开发者在文件删除操作前修改或处理文件路径,常用于扩展删除功能。

关键要点

  • 过滤器名称:wp_delete_file
  • 参数:$file(字符串类型,表示要删除的文件路径)
  • 用途:在 wp_delete_file() 函数中应用,用于自定义文件删除行为
  • 引入版本:WordPress 2.1.0

代码示例

/* 当删除图像文件时,同时删除对应的 .webp 版本(如果存在) */
add_filter( 'wp_delete_file', function ( string $file ): string {
  return preg_replace_callback( '/^(.+.)(?:bmp|gif|jpe?g|pdf|png)$/i', function ( array $matches ): string {
    wp_delete_file( $matches[1] . 'webp' );
    return $matches[0];
  }, $file );
} );

注意事项

  • 此过滤器在 wp_delete_file() 函数内部调用,用于修改传入的文件路径
  • 示例代码展示了如何利用过滤器在删除标准图像格式时自动删除对应的 .webp 文件
  • 确保过滤器函数返回一个字符串路径,否则可能影响文件删除操作

📄 原文内容

Filters the path of the file to delete.

Parameters

$filestring
Path to the file to delete.

Source

$delete = apply_filters( 'wp_delete_file', $file );

Changelog

Version Description
2.1.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Here’s a quick one-liner using this filter that I wrote for a site that serves .webp images as well as whatever jpeg or png was uploaded to WordPress. When any image file is deleted, it also deletes the .webp version, if it exists. e.g. when you delete an image such as /uploads/2024/01/example.png from the Media Library, it will also delete /uploads/2024/01/example.webp.

    /* When image files are deleted, also delete the .webp version, when it exists */
    add_filter( 'wp_delete_file', function ( string $file ): string {
      return preg_replace_callback( '/^(.+.)(?:bmp|gif|jpe?g|pdf|png)$/i', function ( array $matches ): string {
        wp_delete_file( $matches[1] . 'webp' );
        return $matches[0];
      }, $file );
    } );