Review my code for setting featured image
-
I have a form which the user uploads an image file to. The form takes the file and puts it in “wp-content/uploads/gravity_forms/” folder. The form then returns the URL of the file. I need to set that file as a featured image to a given post. So these are known: $post_id and $file_url.
This is my code, after reading the codex about wp_insert_attachment:
$filename = basename( $file_url ); $filetype = wp_check_filetype( $filename, null ); $wp_upload_dir = wp_upload_dir(); $attachment = array( 'guid' => $wp_upload_dir['url'] . '/' . $filename, 'post_mime_type' => $filetype['type'], 'post_title' => $filename, 'post_content' => '', 'post_status' => 'inherit' ); $attach_id = wp_insert_attachment( $attachment, $file_url, $post_id ); require_once( ABSPATH . 'wp-admin/includes/image.php' ); $attach_data = wp_generate_attachment_metadata( $attach_id, $file_url ); wp_update_attachment_metadata( $attach_id, $attach_data ); set_post_thumbnail( $post_id, $attach_id );
Is it good?
- The topic ‘Review my code for setting featured image’ is closed to new replies.