PHP WordPress Generate Thumbnail By Url Without Extension
I recently faced this issue where the normal way of downloading images from a url, and then attaching it as a thumbnail, didn’t work out. This was because the link of the image was generated by a .php script, hence it didn’t have any image extension at the end, such as ‘.jpeg’.
The normal way didn’t work, because the call on media_handle_sideload
, would eventually lead to _wp_handle_upload
, which does a sanity check by calling is_uploaded_file
, a php function, producing the error WP_Error
that says ‘Specified file failed upload test.’
After much trial and error, I finally came up with a way to accomplish this (albeit with some small hacks). That is, to simply prepend our extension (.jpeg/.png/.whatever image type) to the filename that we want, while avoiding the use of the function media_handle_sideload
.
The code is as shown below. Currently, what it does is to ensure firstly that the filename
has an extension, then manually download the image file through file_get_contents
, before uploading it to WordPress via wp_upload_bits
, before inserting and performing other attachment related stuff.
public function generate_featured_image_1( $file_url, $post_id, $desc ) { /* * $file is the path to your uploaded file (for example as set in the $_FILE posted file array) * $filename is the name of the file * first we need to upload the file into the wp upload folder. */ $filename = basename($file_url); if( stristr($filename, '.jpeg') ) { // you might want to make it so that it supports more extension, etc.. } else { $filename .= ".jpeg"; } $upload_file = wp_upload_bits( $filename, null, @file_get_contents( $file_url ) ); Debug::pretty_dump($upload_file); if ( ! $upload_file['error'] ) { // if succesfull insert the new file into the media library (create a new attachment post type). $wp_filetype = wp_check_filetype($filename, null ); $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_parent' => $post_id, 'post_title' => preg_replace( '/\.[^.]+$/', '', $filename ), 'post_content' => '', 'post_status' => 'inherit' ); $attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], $post_id ); if ( ! is_wp_error( $attachment_id ) ) { // if attachment post was successfully created, insert it as a thumbnail to the post $post_id. require_once(ABSPATH . "wp-admin" . '/includes/image.php'); $attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] ); wp_update_attachment_metadata( $attachment_id, $attachment_data ); $alt_meta_id = update_post_meta($attachment_id, '_wp_attachment_image_alt', $desc); //https://developer.wordpress.org/reference/functions/update_post_meta/ return set_post_thumbnail( $post_id, $attachment_id ); } else { $error_string = $attachment_id->get_error_message(); echo '<div id="message" class="error"><p>' . $error_string . '</p></div>'; } } else { echo "error: " . $upload_file['error']; } return false; }
Be First to Comment