函数文档

get_attached_file()

💡 云策文档标注

概述

get_attached_file() 函数用于根据附件 ID 检索附件的文件路径。它通过获取 _wp_attached_file 元数据值实现,并支持通过 'get_attached_file' 过滤器进行修改。

关键要点

  • 函数基于附件 ID 返回文件路径,若路径为相对路径,则自动添加上传目录前缀。
  • 参数 $unfiltered 控制是否跳过 'get_attached_file' 过滤器,默认值为 false。
  • 返回值为字符串(文件路径)或 false(失败时)。
  • 内部使用 get_post_meta() 获取元数据,并应用 apply_filters() 钩子。

代码示例

$fullsize_path = get_attached_file( $attachment_id ); // 完整路径
$filename_only = basename( get_attached_file( $attachment_id ) ); // 仅文件名

📄 原文内容

Retrieves attached file path based on attachment ID.

Description

By default the path will go through the ‘get_attached_file’ filter, but passing true to the $unfiltered argument will return the file path unfiltered.

The function works by retrieving the _wp_attached_file post meta value.
This is a convenience function to prevent looking up the meta name and provide a mechanism for sending the attached filename through a filter.

Parameters

$attachment_idintrequired
Attachment ID.
$unfilteredbooloptional
Whether to skip the ‘get_attached_file’ filter.

Default:false

Return

string|false The file path to where the attached file should be, false otherwise.

Source

function get_attached_file( $attachment_id, $unfiltered = false ) {
	$file = get_post_meta( $attachment_id, '_wp_attached_file', true );

	// If the file is relative, prepend upload dir.
	if ( $file && ! str_starts_with( $file, '/' ) && ! preg_match( '|^.:\|', $file ) ) {
		$uploads = wp_get_upload_dir();
		if ( false === $uploads['error'] ) {
			$file = $uploads['basedir'] . "/$file";
		}
	}

	if ( $unfiltered ) {
		return $file;
	}

	/**
	 * Filters the attached file based on the given ID.
	 *
	 * @since 2.1.0
	 *
	 * @param string|false $file          The file path to where the attached file should be, false otherwise.
	 * @param int          $attachment_id Attachment ID.
	 */
	return apply_filters( 'get_attached_file', $file, $attachment_id );
}

Hooks

apply_filters( ‘get_attached_file’, string|false $file, int $attachment_id )

Filters the attached file based on the given ID.

Changelog

Version Description
2.0.0 Introduced.

User Contributed Notes