wp_maybe_generate_attachment_metadata() WordPress Function

The wp_maybe_generate_attachment_metadata() function allows you to check if an attachment has metadata and if not, generate it. This can be useful when you want to ensure that an attachment has all the necessary data before displaying it on your website.

wp_maybe_generate_attachment_metadata( WP_Post $attachment ) #

Maybe attempts to generate attachment metadata, if missing.


Parameters

$attachment

(WP_Post)(Required)Attachment object.


Top ↑

Source

File: wp-includes/media.php

function wp_maybe_generate_attachment_metadata( $attachment ) {
	if ( empty( $attachment ) || empty( $attachment->ID ) ) {
		return;
	}

	$attachment_id = (int) $attachment->ID;
	$file          = get_attached_file( $attachment_id );
	$meta          = wp_get_attachment_metadata( $attachment_id );

	if ( empty( $meta ) && file_exists( $file ) ) {
		$_meta = get_post_meta( $attachment_id );
		$_lock = 'wp_generating_att_' . $attachment_id;

		if ( ! array_key_exists( '_wp_attachment_metadata', $_meta ) && ! get_transient( $_lock ) ) {
			set_transient( $_lock, $file );
			wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
			delete_transient( $_lock );
		}
	}
}


Top ↑

Changelog

Changelog
VersionDescription
3.9.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More