Last active
July 2, 2021 16:51
-
-
Save jackabox/12845d584a8085e10d699cba53f8d86a to your computer and use it in GitHub Desktop.
generate a post_thumbnail (and upload) from a 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 | |
| function upload_thumbnail($image_url, $postID) { | |
| // Add Featured Image to Post | |
| $upload_dir = wp_upload_dir(); // Set upload folder | |
| $image_data = file_get_contents($image_url); // Get image data | |
| $filename = basename($image_url); // Create image file name | |
| // $filename = strstr($filename, '?', true); // we stripped the cache from instagram | |
| // Check folder permission and define file location | |
| if( wp_mkdir_p( $upload_dir['path'] ) ) { | |
| $file = $upload_dir['path'] . '/' . basename($filename); | |
| } else { | |
| $file = $upload_dir['basedir'] . '/' . basename($filename); | |
| } | |
| // Create the image file on the server | |
| file_put_contents( $file, $image_data ); | |
| // Check image file type | |
| $wp_filetype = wp_check_filetype( $filename, null ); | |
| // Set attachment data | |
| $attachment = array( | |
| 'post_mime_type' => $wp_filetype['type'], | |
| 'post_title' => sanitize_file_name( $filename ), | |
| 'post_content' => '', | |
| 'post_status' => 'inherit' | |
| ); | |
| // Create the attachment | |
| $attach_id = wp_insert_attachment( $attachment, $file, $postID ); | |
| require_once(ABSPATH . 'wp-admin/includes/image.php'); | |
| $attach_data = wp_generate_attachment_metadata( $attach_id, $file ); | |
| wp_update_attachment_metadata( $attach_id, $attach_data ); | |
| set_post_thumbnail( $postID, $attach_id ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment