函数文档

wp_update_attachment_metadata()

💡 云策文档标注

概述

wp_update_attachment_metadata() 函数用于更新附件的元数据,通过修改 _wp_attachment_metadata 元字段实现。它接受附件ID和元数据数组作为参数,并返回更新状态或元ID。

关键要点

  • 参数:$attachment_id(整数,必需,附件文章ID)和 $data(数组,必需,附件元数据)。
  • 返回值:成功时返回 true 或新元ID(如果键不存在),失败时返回 false(如文章无效或数据未变)。
  • 内部流程:先获取文章对象,应用 wp_update_attachment_metadata 过滤器,然后调用 update_post_meta() 或 delete_post_meta() 更新元数据。
  • 相关函数:与 update_post_meta()、delete_post_meta()、apply_filters() 和 get_post() 紧密关联。
  • 使用场景:广泛用于图像处理、REST API、自定义界面等,如生成图像子尺寸、处理上传文件等。

代码示例

function wp_update_attachment_metadata( $attachment_id, $data ) {
    $attachment_id = (int) $attachment_id;
    $post = get_post( $attachment_id );
    if ( ! $post ) {
        return false;
    }
    $data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID );
    if ( $data ) {
        return update_post_meta( $post->ID, '_wp_attachment_metadata', $data );
    } else {
        return delete_post_meta( $post->ID, '_wp_attachment_metadata' );
    }
}

注意事项

  • 确保 $attachment_id 对应有效附件文章,否则函数返回 false。
  • 数据通过 wp_update_attachment_metadata 过滤器可被修改,开发者可挂钩此过滤器自定义元数据。
  • 如果 $data 为空数组,函数会删除 _wp_attachment_metadata 元字段。
  • 自 WordPress 2.1.0 版本引入,保持向后兼容。

📄 原文内容

Updates metadata for an attachment.

Parameters

$attachment_idintrequired
Attachment post ID.
$dataarrayrequired
Attachment meta data.

Return

int|bool Whether the metadata was successfully updated.
True on success, the Meta ID if the key didn’t exist.
False if $post is invalid, on failure, or if $data is the same as the existing metadata.

Source

function wp_update_attachment_metadata( $attachment_id, $data ) {
	$attachment_id = (int) $attachment_id;

	$post = get_post( $attachment_id );

	if ( ! $post ) {
		return false;
	}

	/**
	 * Filters the updated attachment meta data.
	 *
	 * @since 2.1.0
	 *
	 * @param array $data          Array of updated attachment meta data.
	 * @param int   $attachment_id Attachment post ID.
	 */
	$data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID );
	if ( $data ) {
		return update_post_meta( $post->ID, '_wp_attachment_metadata', $data );
	} else {
		return delete_post_meta( $post->ID, '_wp_attachment_metadata' );
	}
}

Hooks

apply_filters( ‘wp_update_attachment_metadata’, array $data, int $attachment_id )

Filters the updated attachment meta data.

Changelog

Version Description
2.1.0 Introduced.