Created
January 30, 2020 00:05
-
-
Save saltnpixels/5e2253888dbb26f8e7190ebcf252f95c to your computer and use it in GitHub Desktop.
WP Upload URL to Media Library
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 | |
/** | |
* @param $url url to upload | |
* @param int $post_id post to attach it to | |
* | |
* Add a url to the media library and attach it to a post if wanted | |
* @return bool|int|string|WP_Error | |
*/ | |
function upload_url( $url, $post_id = 0 ) { | |
require_once( ABSPATH . 'wp-admin/includes/image.php' ); | |
require_once( ABSPATH . 'wp-admin/includes/file.php' ); | |
require_once( ABSPATH . 'wp-admin/includes/media.php' ); | |
$temp_file = download_url( $url ); | |
if ( is_wp_error( $temp_file ) ) { | |
@unlink( $temp_file ); | |
return $temp_file; | |
} | |
$file_type = wp_check_filetype( $url ); | |
if ( ! is_wp_error( $temp_file ) ) { | |
// Create Array based on $_FILE with php | |
$file = array( | |
'name' => basename( $url ), // ex: wp-header-logo.png | |
'type' => $file_type['type'], | |
'tmp_name' => $temp_file, | |
'error' => 0, | |
'size' => filesize( $temp_file ), | |
); | |
$attachment_id = media_handle_sideload( $file, $post_id ); | |
@unlink( $temp_file ); | |
return $attachment_id; | |
} | |
return false; | |
} | |
//Some stuff you can do with the returned ID | |
//update_post_meta( $attachment_id, '_wp_attachment_image_alt', sanitize_title_with_dashes( get_the_title( $post_id ) ) ); | |
//set_post_thumbnail( $post_id, $attachment_id ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment