wp_update_attachment_metadata()WP 2.1.0

Update metadata for an attachment.

Hooks from the function

Return

Int|false. False if $post is invalid.

Usage

wp_update_attachment_metadata( $attachment_id, $data );
$attachment_id(int) (required)
Attachment post ID.
$data(array) (required)
Attachment meta data.

Examples

0

#1 Update the image caption

Let's add our data to the image with ID 656. To do this, first get the metadata, change it (add your own data), and save it:

$attach_id = 656;

$data = wp_get_attachment_metadata( $attach_id );

// set the custom data
$data['image_meta']['my_data'] = 'This (string) of data I will need';

// update data
$up = wp_update_attachment_metadata( $attach_id, $data );

echo $up ? 'Updated' : 'Not updated';

The $data was equal to following array when was updating:

Array
(
	[width] => 356
	[height] => 299
	[file] => 2011/05/dinamic-archives.png
	[sizes] => Array
		(
			[thumbnail] => Array
				(
					[file] => dinamic-archives-80x80.png
					[width] => 80
					[height] => 80
					[mime-type] => image/png
				)

			[medium] => Array
				(
					[file] => dinamic-archives-120x100.png
					[width] => 120
					[height] => 100
					[mime-type] => image/png
				)

		)

	[image_meta] => Array
		(
			[aperture] => 0
			[credit] => 
			[camera] => 
			[caption] => 
			[created_timestamp] => 0
			[copyright] => 
			[focal_length] => 0
			[iso] => 0
			[shutter_speed] => 0
			[title] => 
			[my_data] => This (string) of data I will need
		)

)

Changelog

Since 2.1.0 Introduced.

Code of wp_update_attachment_metadata() WP 6.0.1

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' );
	}
}