I have implemented a front-end form to submit posts. The image upload is handled with the Wordpress Media Library
- Users click on "Upload Image"
- Media Library opens
- Users either select an existing image or upload a new one
- The path to the image (URL) gets populated into an
<input>
field
Problem: My question concerns the featured image: If users choose an existing image from the Media Library, this image get's added to the Media Library again, which I wanted to avoid for two reasons:
a) Save disk space
- Right now I have one image saved twice:
http://localhost/?attachment_id=2523
as well ashttp://localhost/images/picture.jpg
b) Avoiding duplicates in Media Lirbary
- Users can access the Media Library from the front-end and I don't want them so see duplicate images
Is it possible to assign one image as a featured image to multiple posts?
Here's what I got:
// $featuredimg contains the URL to the image: http://mydomain.com/wp-content/uploads...
$filetype = wp_check_filetype( basename( $featuredimg ), null );
$wp_upload_dir = wp_upload_dir();
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $featuredimg ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $featuredimg ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$thumb_id = wp_insert_attachment( $attachment, $featuredimg, $pid );
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $thumb_id, $featuredimg );
wp_update_attachment_metadata( $thumb_id, $attach_data );
update_post_meta( $pid, '_thumbnail_id', $thumb_id );