$url = "http://i.imgur.com/LNWnPxA.png";
$post_ID = "1"; // Post number ID
$image_id = wp_insert_attachment_by_url( $url, $post_ID );
if ( ! is_wp_error( $image_id ) ) {
/**
* Show ID Thumbnail
* Use "wp_get_attachment_url" to get url.
*/
print_r( $image_id ); // Show ID Thumbnail
} else {
print_r( $image_id ); // Show Error
}
Last active
September 3, 2021 12:52
-
-
Save lenivene/22691fee7b8e95619055e59793228b09 to your computer and use it in GitHub Desktop.
Insert thumbnail (attachment) post by url
This file contains hidden or 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 | |
/** | |
* Insert thumbnail by URL | |
* Is very good to execute wp_insert_post | |
* | |
* @author Lenivene Bezerra | |
* @param string $url Image url external or no | |
* @param int $post_ID Post id to insert thumbnail | |
* @return ID Thumbnail | WP_Error | |
*/ | |
function wp_insert_attachment_by_url( $url, $post_ID ) { | |
require_once( ABSPATH . 'wp-admin/includes/media.php' ); | |
require_once( ABSPATH . 'wp-admin/includes/file.php' ); | |
require_once( ABSPATH . 'wp-admin/includes/image.php' ); | |
if ( '' == $post_ID ) | |
return new WP_Error( 'insert_attachment_failed', __( 'Invalid post ID' ) ); | |
if( !empty( $url ) ){ | |
$url = esc_url( $url ); | |
/** | |
* Set variables for storage, fix file | |
* filename for query strings. | |
*/ | |
preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $url, $matches ); | |
if ( ! $matches ) { | |
return new WP_Error( 'insert_attachment_failed', __( 'Invalid image URL' ) ); | |
} | |
$file_array = array(); | |
$file_array['name'] = basename( $matches[0] ); | |
/** | |
* Download file to temp location. | |
*/ | |
$file_array['tmp_name'] = download_url( $url ); | |
/** | |
* Check for download errors | |
* if there are error unlink the temp file name | |
*/ | |
if ( is_wp_error( $file_array['tmp_name'] ) ) { | |
return $file_array['tmp_name']; | |
} | |
$image_ID = media_handle_sideload( $file_array, $post_ID ); | |
/** | |
* If error storing permanently, unlink. | |
*/ | |
if ( is_wp_error( $image_ID ) ) { | |
@unlink( $file_array['tmp_name'] ); | |
return $image_ID; | |
} | |
/** | |
* If error thumbnail | |
*/ | |
if ( false === set_post_thumbnail( $post_ID, $image_ID ) ) { | |
return new WP_Error( 'insert_attachment_failed', __( 'Problem to set post thumbnail' ) ); | |
} | |
return $image_ID; | |
}else{ | |
return new WP_Error( 'insert_attachment_failed', __( 'Insert URL' ) ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment