Customizer: Minimize duplicate header crops in the media library.

This adds `Custom_Image_Header::get_previous_crop()`, which finds any
previously cropped headers created from the same base image and replaces
that attachment rather than creating a new attachment.

After updating a crop, the replaced images is also removed from the list
of previous header images in the Customizer.

See #21819.


git-svn-id: https://develop.svn.wordpress.org/trunk@41732 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Joe McGill
2017-10-04 14:58:07 +00:00
parent d77da9cd2a
commit 59c0329461
4 changed files with 100 additions and 2 deletions
+46 -2
View File
@@ -1164,7 +1164,8 @@ wp_nonce_field( 'custom-header-options', '_wpnonce-custom-header-options' ); ?>
'post_title' => basename($cropped),
'post_mime_type' => $image_type,
'guid' => $url,
'context' => 'custom-header'
'context' => 'custom-header',
'post_parent' => $parent_attachment_id,
);
return $object;
@@ -1180,8 +1181,12 @@ wp_nonce_field( 'custom-header-options', '_wpnonce-custom-header-options' ); ?>
* @return int Attachment ID.
*/
final public function insert_attachment( $object, $cropped ) {
$parent_id = isset( $object['post_parent'] ) ? $object['post_parent'] : null;
unset( $object['post_parent'] );
$attachment_id = wp_insert_attachment( $object, $cropped );
$metadata = wp_generate_attachment_metadata( $attachment_id, $cropped );
/**
* Filters the header image attachment metadata.
*
@@ -1193,6 +1198,11 @@ wp_nonce_field( 'custom-header-options', '_wpnonce-custom-header-options' ); ?>
*/
$metadata = apply_filters( 'wp_header_image_attachment_metadata', $metadata );
wp_update_attachment_metadata( $attachment_id, $metadata );
if ( $parent_id ) {
$meta = add_post_meta( $attachment_id, '_wp_attachment_parent', $parent_id, true );
}
return $attachment_id;
}
@@ -1241,7 +1251,13 @@ wp_nonce_field( 'custom-header-options', '_wpnonce-custom-header-options' ); ?>
$object = $this->create_attachment_object( $cropped, $attachment_id );
unset( $object['ID'] );
$previous = $this->get_previous_crop( $object );
if ( $previous ) {
$object['ID'] = $previous;
} else {
unset( $object['ID'] );
}
$new_attachment_id = $this->insert_attachment( $object, $cropped );
@@ -1396,4 +1412,32 @@ wp_nonce_field( 'custom-header-options', '_wpnonce-custom-header-options' ); ?>
return $header_images;
}
/**
* Get the ID of a previous crop from the same base image.
*
* @since 4.9.0
*
* @param array $object A crop attachment object.
* @return int|false An attachment ID if one exists. False if none.
*/
public function get_previous_crop( $object ) {
$header_images = $this->get_uploaded_header_images();
// Bail early if there are no header images.
if ( empty( $header_images ) ) {
return false;
}
$previous = false;
foreach ( $header_images as $image ) {
if ( $image['attachment_parent'] === $object['post_parent'] ) {
$previous = $image['attachment_id'];
break;
}
}
return $previous;
}
}