- $ext = '.jpg';
- switch ( $metadata['image']['mime'] ) {
- case 'image/gif':
- $ext = '.gif';
- break;
- case 'image/png':
- $ext = '.png';
- break;
- }
- $basename = str_replace( '.', '-', basename( $file ) ) . '-image' . $ext;
- $uploaded = wp_upload_bits( $basename, '', $metadata['image']['data'] );
- if ( false === $uploaded['error'] ) {
- $attachment = array(
- 'post_mime_type' => $metadata['image']['mime'],
- 'post_type' => 'attachment',
- 'post_content' => '',
- );
- $sub_attachment_id = wp_insert_attachment( $attachment, $uploaded['file'] );
- $attach_data = wp_generate_attachment_metadata( $sub_attachment_id, $uploaded['file'] );
- wp_update_attachment_metadata( $sub_attachment_id, $attach_data );
- update_post_meta( $attachment_id, '_thumbnail_id', $sub_attachment_id );
+ // Check for existing cover.
+ $hash = md5( $metadata['image']['data'] );
+ $posts = get_posts( array(
+ 'fields' => 'ids',
+ 'post_type' => 'attachment',
+ 'post_mime_type' => $metadata['image']['mime'],
+ 'post_status' => 'inherit',
+ 'posts_per_page' => 1,
+ 'meta_key' => '_cover_hash',
+ 'meta_value' => $hash
+ ) );
+ $exists = reset( $posts );
+
+ if ( ! empty( $exists ) ) {
+ update_post_meta( $attachment_id, '_thumbnail_id', $exists );
+ } else {
+ $ext = '.jpg';
+ switch ( $metadata['image']['mime'] ) {
+ case 'image/gif':
+ $ext = '.gif';
+ break;
+ case 'image/png':
+ $ext = '.png';
+ break;
+ }
+ $basename = str_replace( '.', '-', basename( $file ) ) . '-image' . $ext;
+ $uploaded = wp_upload_bits( $basename, '', $metadata['image']['data'] );
+ if ( false === $uploaded['error'] ) {
+ $image_attachment = array(
+ 'post_mime_type' => $metadata['image']['mime'],
+ 'post_type' => 'attachment',
+ 'post_content' => '',
+ );
+ /**
+ * Filter the parameters for the attachment thumbnail creation.
+ *
+ * @since 3.9.0
+ *
+ * @param array $image_attachment An array of parameters to create the thumbnail.
+ * @param array $metadata Current attachment metadata.
+ * @param array $uploaded An array containing the thumbnail path and url.
+ */
+ $image_attachment = apply_filters( 'attachment_thumbnail_args', $image_attachment, $metadata, $uploaded );
+
+ $sub_attachment_id = wp_insert_attachment( $image_attachment, $uploaded['file'] );
+ add_post_meta( $sub_attachment_id, '_cover_hash', $hash );
+ $attach_data = wp_generate_attachment_metadata( $sub_attachment_id, $uploaded['file'] );
+ wp_update_attachment_metadata( $sub_attachment_id, $attach_data );
+ update_post_meta( $attachment_id, '_thumbnail_id', $sub_attachment_id );
+ }