函数文档

wp_filesize()

💡 云策文档标注

概述

wp_filesize() 是 WordPress 中用于获取文件大小的函数,它封装了 PHP 的 filesize 函数,并添加了过滤器和整数类型转换功能。

关键要点

  • 函数接受一个必需参数 $path,表示文件路径。
  • 返回值为整数,表示文件大小(字节),出错时返回 0。
  • 提供了两个过滤器:pre_wp_filesize 在 PHP filesize 调用前运行,允许提前返回自定义大小;wp_filesize 在获取大小后运行,用于修改结果。
  • 函数内部会检查文件是否存在,不存在则返回 0。

代码示例

function wp_filesize( $path ) {
    $size = apply_filters( 'pre_wp_filesize', null, $path );
    if ( is_int( $size ) ) {
        return $size;
    }
    $size = file_exists( $path ) ? (int) filesize( $path ) : 0;
    return (int) apply_filters( 'wp_filesize', $size, $path );
}

注意事项

该函数自 WordPress 6.0.0 版本引入,常用于处理附件、图像编辑等场景,确保文件大小以整数形式返回,便于后续处理。


📄 原文内容

Wrapper for PHP filesize with filters and casting the result as an integer.

Parameters

$pathstringrequired
Path to the file.

Return

int The size of the file in bytes, or 0 in the event of an error.

Source

function wp_filesize( $path ) {
	/**
	 * Filters the result of wp_filesize before the PHP function is run.
	 *
	 * @since 6.0.0
	 *
	 * @param null|int $size The unfiltered value. Returning an int from the callback bypasses the filesize call.
	 * @param string   $path Path to the file.
	 */
	$size = apply_filters( 'pre_wp_filesize', null, $path );

	if ( is_int( $size ) ) {
		return $size;
	}

	$size = file_exists( $path ) ? (int) filesize( $path ) : 0;

	/**
	 * Filters the size of the file.
	 *
	 * @since 6.0.0
	 *
	 * @param int    $size The result of PHP filesize on the file.
	 * @param string $path Path to the file.
	 */
	return (int) apply_filters( 'wp_filesize', $size, $path );
}

Hooks

apply_filters( ‘pre_wp_filesize’, null|int $size, string $path )

Filters the result of wp_filesize before the PHP function is run.

apply_filters( ‘wp_filesize’, int $size, string $path )

Filters the size of the file.

Changelog

Version Description
6.0.0 Introduced.