137 | | $ext = '.jpg'; |
138 | | switch ( $metadata['image']['mime'] ) { |
139 | | case 'image/gif': |
140 | | $ext = '.gif'; |
141 | | break; |
142 | | case 'image/png': |
143 | | $ext = '.png'; |
144 | | break; |
| 137 | // check for existing cover |
| 138 | $hash = md5( $metadata['image']['data'] ); |
| 139 | global $wpdb; |
| 140 | $sql = $wpdb->prepare( |
| 141 | "SELECT ID FROM $wpdb->posts WHERE post_type = 'attachment' AND post_mime_type = %s AND post_content_filtered = %s", |
| 142 | $metadata['image']['mime'], |
| 143 | $hash |
| 144 | ); |
| 145 | $exists = $wpdb->get_var( $sql ); |
| 146 | if ( $exists ) { |
| 147 | update_post_meta( $attachment_id, '_thumbnail_id', $exists ); |
| 148 | } else { |
| 149 | $ext = '.jpg'; |
| 150 | switch ( $metadata['image']['mime'] ) { |
| 151 | case 'image/gif': |
| 152 | $ext = '.gif'; |
| 153 | break; |
| 154 | case 'image/png': |
| 155 | $ext = '.png'; |
| 156 | break; |
| 157 | } |
| 158 | $basename = str_replace( '.', '-', basename( $file ) ) . '-image' . $ext; |
| 159 | $uploaded = wp_upload_bits( $basename, '', $metadata['image']['data'] ); |
| 160 | if ( false === $uploaded['error'] ) { |
| 161 | $attachment = array( |
| 162 | 'post_mime_type' => $metadata['image']['mime'], |
| 163 | 'post_type' => 'attachment', |
| 164 | 'post_content' => '', |
| 165 | 'post_content_filtered' => $hash |
| 166 | ); |
| 167 | $sub_attachment_id = wp_insert_attachment( $attachment, $uploaded['file'] ); |
| 168 | $attach_data = wp_generate_attachment_metadata( $sub_attachment_id, $uploaded['file'] ); |
| 169 | wp_update_attachment_metadata( $sub_attachment_id, $attach_data ); |
| 170 | update_post_meta( $attachment_id, '_thumbnail_id', $sub_attachment_id ); |
| 171 | } |
146 | | $basename = str_replace( '.', '-', basename( $file ) ) . '-image' . $ext; |
147 | | $uploaded = wp_upload_bits( $basename, '', $metadata['image']['data'] ); |
148 | | if ( false === $uploaded['error'] ) { |
149 | | $attachment = array( |
150 | | 'post_mime_type' => $metadata['image']['mime'], |
151 | | 'post_type' => 'attachment', |
152 | | 'post_content' => '', |
153 | | ); |
154 | | $sub_attachment_id = wp_insert_attachment( $attachment, $uploaded['file'] ); |
155 | | $attach_data = wp_generate_attachment_metadata( $sub_attachment_id, $uploaded['file'] ); |
156 | | wp_update_attachment_metadata( $sub_attachment_id, $attach_data ); |
157 | | update_post_meta( $attachment_id, '_thumbnail_id', $sub_attachment_id ); |
158 | | } |