Last active
February 18, 2020 08:28
-
-
Save vanpariyar/1206af29f562e5e50ca7f9a172f28687 to your computer and use it in GitHub Desktop.
POST THUMBNAIL OR FILE UPLOADING FROM THE FRONT END
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
/*POST THUMBNAIL OR FILE UPLOADING FROM THE FRONT END*/ | |
function textDomain_thumbnail_uploading_function( $file, $post_id , $set_as_featured = false ) { | |
require( ABSPATH.'/wp-load.php' ); | |
if ( !function_exists('wp_handle_upload') ) { | |
require_once(ABSPATH . 'wp-admin/includes/file.php'); | |
} | |
$upload = wp_upload_bits( $file['name'], null, file_get_contents( $file['tmp_name'] ) ); | |
$wp_filetype = wp_check_filetype( basename( $upload['file'] ), null ); | |
$wp_upload_dir = wp_upload_dir(); | |
$attachment = array( | |
'guid' => $wp_upload_dir['baseurl'] . _wp_relative_upload_path( $upload['file'] ), | |
'post_mime_type' => $wp_filetype['type'], | |
'post_title' => preg_replace('/\.[^.]+$/', '', basename( $upload['file'] )), | |
'post_content' => '', | |
'post_status' => 'inherit' | |
); | |
$attachment_id = wp_insert_attachment( $attachment, $upload['file'], $post_id ); | |
require_once(ABSPATH . 'wp-admin/includes/image.php'); | |
$attach_data = wp_generate_attachment_metadata( $attachment_id, $upload['file'] ); | |
wp_update_attachment_metadata( $attachment_id, $attach_data ); | |
if( $set_as_featured == true ) { | |
set_post_thumbnail( $post_id, $attachment_id ); | |
} | |
return $attachment_id; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment