wp_maybe_generate_attachment_metadata()
Creates attachment metadata if it is missing; otherwise, does nothing.
The function will add metadata to the meta-fields (see wp_update_attachment_metadata()), only if:
- Metadata is not present yet - wp_get_attachment_metadata() returns nothing.
- The file physically exists - the path for checking the file is obtained through get_attached_file().
Uses: get_attached_file(), wp_get_attachment_metadata(), wp_update_attachment_metadata(), wp_generate_attachment_metadata()
No Hooks.
Returns
null. Nothing.
Usage
wp_maybe_generate_attachment_metadata( $attachment );
- $attachment(WP_Post) (required)
- The attachment object for which metadata needs to be generated.
Examples
#1 Generation of attachment metadata
This example shows how to create metadata for a file added to the media library. It assumes that the metadata was not created automatically for some reason (usually it is created automatically). If the data already exists (function wp_get_attachment_metadata() returns something), the function will simply do nothing.
$attachment = get_post( 123 ); wp_maybe_generate_attachment_metadata( $attachment );
Changelog
| Since 3.9.0 | Introduced. |
wp_maybe_generate_attachment_metadata() wp maybe generate attachment metadata code WP 6.9.1
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 );
}
}
}