Skip to content

Instantly share code, notes, and snippets.

@saltnpixels
Created January 30, 2020 00:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saltnpixels/5e2253888dbb26f8e7190ebcf252f95c to your computer and use it in GitHub Desktop.
Save saltnpixels/5e2253888dbb26f8e7190ebcf252f95c to your computer and use it in GitHub Desktop.
WP Upload URL to Media Library
<?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