-
-
Save m1r0/f22d5237ee93bcccb0d9 to your computer and use it in GitHub Desktop.
<?php | |
/** | |
* Insert an attachment from a URL address. | |
* | |
* @param string $url The URL address. | |
* @param int|null $parent_post_id The parent post ID (Optional). | |
* @return int|false The attachment ID on success. False on failure. | |
*/ | |
function wp_insert_attachment_from_url( $url, $parent_post_id = null ) { | |
if ( ! class_exists( 'WP_Http' ) ) { | |
require_once ABSPATH . WPINC . '/class-http.php'; | |
} | |
$http = new WP_Http(); | |
$response = $http->request( $url ); | |
if ( 200 !== $response['response']['code'] ) { | |
return false; | |
} | |
$upload = wp_upload_bits( basename( $url ), null, $response['body'] ); | |
if ( ! empty( $upload['error'] ) ) { | |
return false; | |
} | |
$file_path = $upload['file']; | |
$file_name = basename( $file_path ); | |
$file_type = wp_check_filetype( $file_name, null ); | |
$attachment_title = sanitize_file_name( pathinfo( $file_name, PATHINFO_FILENAME ) ); | |
$wp_upload_dir = wp_upload_dir(); | |
$post_info = array( | |
'guid' => $wp_upload_dir['url'] . '/' . $file_name, | |
'post_mime_type' => $file_type['type'], | |
'post_title' => $attachment_title, | |
'post_content' => '', | |
'post_status' => 'inherit', | |
); | |
// Create the attachment. | |
$attach_id = wp_insert_attachment( $post_info, $file_path, $parent_post_id ); | |
// Include image.php. | |
require_once ABSPATH . 'wp-admin/includes/image.php'; | |
// Generate the attachment metadata. | |
$attach_data = wp_generate_attachment_metadata( $attach_id, $file_path ); | |
// Assign metadata to attachment. | |
wp_update_attachment_metadata( $attach_id, $attach_data ); | |
return $attach_id; | |
} |
I'm really new to this but was wondering where I should insert this snippet into? Another file or save the whole php file into a certain folder.
Works perfectly, thanks bro ^^
Very very very nice work!
Thanks bro!
Thanks alot!!!
Genial, funcionó perfecto!!!! Gracias
This is killer. Thank you!
if facing function error. you need to include these two files.
include(ABSPATH . "wp-includes/pluggable.php");
include_once( ABSPATH . '/wp-admin/includes/image.php' );
In addition add a slash to the class instance if you are on a namespaced class
$http = new \WP_Http();
if facing function error. you need to include these two files.
include(ABSPATH . "wp-includes/pluggable.php"); include_once( ABSPATH . '/wp-admin/includes/image.php' );
In addition add a slash to the class instance if you are on a namespaced class
$http = new \WP_Http();
I've haven't work with Wordpress in quite a while, but if I'm not mistaken, if you are facing this issue its because you are running the script somewhere where the necessary wordpress functions are not being included. The solution shouldn't be to include the scripts manually, but to run it in the correct environment. Whish I could be of more help, but I'm rusty with Wordpress atm .
hand down thanks
Thankyou!
Very useful