函数文档

update_attached_file()

💡 云策文档标注

概述

update_attached_file() 函数用于根据附件 ID 更新附件文件路径,通过修改 post meta 中的 _wp_attached_file 键值实现。它处理路径的相对化,并返回操作状态。

关键要点

  • 函数接受两个参数:$attachment_id(整数,必需)和 $file(字符串,必需),分别表示附件 ID 和新的文件路径。
  • 返回值:如果 _wp_attached_file 键不存在,返回 Meta ID;成功更新返回 true;失败或文件路径未变化返回 false。
  • 内部使用 _wp_relative_upload_path() 将路径转换为相对路径,并调用 update_post_meta() 或 delete_post_meta() 进行更新。
  • 提供 'update_attached_file' 过滤器钩子,允许在更新前修改文件路径。

代码示例

function update_attached_file( $attachment_id, $file ) {
    if ( ! get_post( $attachment_id ) ) {
        return false;
    }

    $file = apply_filters( 'update_attached_file', $file, $attachment_id );

    $file = _wp_relative_upload_path( $file );
    if ( $file ) {
        return update_post_meta( $attachment_id, '_wp_attached_file', $file );
    } else {
        return delete_post_meta( $attachment_id, '_wp_attached_file' );
    }
}

注意事项

  • 函数首先检查附件 ID 对应的 post 是否存在,不存在则返回 false。
  • 路径转换失败时(如 _wp_relative_upload_path() 返回空),会删除 _wp_attached_file 元数据。
  • 相关函数包括 update_post_meta()、delete_post_meta()、_wp_relative_upload_path() 等,用于底层操作。

📄 原文内容

Updates attachment file path based on attachment ID.

Description

Used to update the file path of the attachment, which uses post meta name _wp_attached_file to store the path of the attachment.

Parameters

$attachment_idintrequired
Attachment ID.
$filestringrequired
File path for the attachment.

Return

int|bool Meta ID if the _wp_attached_file key didn’t exist for the attachment.
True on successful update, false on failure or if the $file value passed to the function is the same as the one that is already in the database.

Source

function update_attached_file( $attachment_id, $file ) {
	if ( ! get_post( $attachment_id ) ) {
		return false;
	}

	/**
	 * Filters the path to the attached file to update.
	 *
	 * @since 2.1.0
	 *
	 * @param string $file          Path to the attached file to update.
	 * @param int    $attachment_id Attachment ID.
	 */
	$file = apply_filters( 'update_attached_file', $file, $attachment_id );

	$file = _wp_relative_upload_path( $file );
	if ( $file ) {
		return update_post_meta( $attachment_id, '_wp_attached_file', $file );
	} else {
		return delete_post_meta( $attachment_id, '_wp_attached_file' );
	}
}

Hooks

apply_filters( ‘update_attached_file’, string $file, int $attachment_id )

Filters the path to the attached file to update.

Changelog

Version Description
2.1.0 Introduced.