03/23/2016 at 10:27 am
#370239
Keymaster
For anyone look to do the same, here’s how:
Install the Code Snippets plugin.
Add a new snippet with the following code:
add_action( 'cn_post_process_add-entry', 'cn_insert_image_into_media_library' );
add_action( 'cn_post_process_update-entry', 'cn_insert_image_into_media_library' );
function cn_insert_image_into_media_library( $entry ) {
$image = $entry->getimageMeta();
if ( ! is_wp_error( $image ) ) {
/*
* Read the contents of the upload directory. We need the
* path to copy the file and the URL for uploading the file.
*/
$uploads = wp_upload_dir();
$uploads_dir = $uploads['path'];
$uploads_url = $uploads['url'];
// Copy the file from the root directory to the uploads directory
copy( $image['path'], trailingslashit( $uploads_dir ) . $image['name'] );
/*
* Get the URL to the file and grab the file and load
* it into WordPress (and the Media Library)
*/
$url = trailingslashit( $uploads_url ) . $image['name'];
$result = media_sideload_image( $url, 0, $image['name'] );
// If there's an error, then we'll write it to the error log.
if ( is_wp_error( $result ) ) {
error_log( print_r( $result, true ) );
}
}
}
Save and Activate the new snippet.
Now, anytime a photo is uploaded, whether it is on an entry being added or an entry being updated, it will be duplicated in the Media Library.
