Created
March 7, 2018 07:11
-
-
Save pramodjodhani/1a9bf9e90743341fa4ac4462d9689e87 to your computer and use it in GitHub Desktop.
This file contains 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 | |
/** | |
==This function will== | |
1. Move the uploaded file to the wordpress upload directory struction | |
2. Add the file in media | |
3. Set the featured image of given post_id | |
==Params== | |
file_input_name: string | |
This parameter is the name of input file input type. | |
ex: <input type='file' name='image'> | |
so the 'image' is the parameter here | |
post_id: Integer | |
The post whose featured image is to be set. | |
Usually the return value of wp_insert_post | |
**/ | |
function wp_upload_file_and_set_featured($file_input_name , $post_id) { | |
if ($_FILES[$file_input_name]['error'] == UPLOAD_ERR_OK //checks for errors | |
&& is_uploaded_file($_FILES[$file_input_name]['tmp_name'])) | |
{ | |
$image_data = file_get_contents($_FILES[$file_input_name]['tmp_name']); | |
$image = $_FILES[$file_input_name]['tmp_name']; | |
$upload_dir = wp_upload_dir(); | |
$image_data = file_get_contents($image); | |
$filename = $_FILES[$file_input_name]['name']; | |
$upload_dir = wp_upload_dir(); | |
if(wp_mkdir_p($upload_dir['path'])) | |
$file = $upload_dir['path'] . '/' . $filename; | |
else | |
$file = $upload_dir['basedir'] . '/' . $filename; | |
file_put_contents($file, $image_data); | |
$wp_filetype = wp_check_filetype($filename, null ); | |
$attachment = array( | |
'post_mime_type' => $wp_filetype['type'], | |
'post_title' => sanitize_file_name($filename), | |
'post_content' => '', | |
'post_status' => 'inherit' | |
); | |
$attach_id = wp_insert_attachment( $attachment, $file, $post_id ); | |
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( $post_id, $attach_id ); | |
if($attach_id) { | |
return true; | |
} | |
else { | |
return false; | |
} | |
} //if file uploaded | |
else { | |
return false; | |
} | |
} // wp_upload_file_and_set_featured |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment