Created
August 2, 2021 02:58
-
-
Save angelorocha/50e3e1759e50702bd29905ce86f33160 to your computer and use it in GitHub Desktop.
Get remote images and save as WordPress attachment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @author Angelo Rocha | |
* @copyleft 2021 | |
* @license GNU GPL 3 (https://www.gnu.org/licenses/gpl-3.0.html) | |
* | |
* @param string $image Set url to get image | |
* | |
*/ | |
function wpss_get_remote_image( string $image ) { | |
$get = wp_remote_get( $image, [ 'timeout' => 120 ] ); | |
$allowed_mimes = [ 'image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml' ]; | |
if ( is_array( $get ) && ! is_wp_error( $get ) ): | |
$mime = wp_remote_retrieve_header( $get, 'content-type' ); | |
if ( in_array( $mime, $allowed_mimes ) ): | |
$upload = wp_upload_bits( basename( $image ), '', wp_remote_retrieve_body( $get ) ); | |
$attach = [ | |
'post_title' => basename( $image ), | |
'guid' => $upload['url'], | |
'post_status' => 'inherit', | |
'post_mime_type' => $mime | |
]; | |
$attach_id = wp_insert_attachment( $attach, $upload['file'] ); | |
require_once( ABSPATH . 'wp-admin/includes/image.php' ); | |
$attach_data = wp_generate_attachment_metadata( $attach_id, $upload['file'] ); | |
wp_update_attachment_metadata( $attach_id, $attach_data ); | |
return $attach_id; | |
endif; | |
endif; | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment