Skip to content

Instantly share code, notes, and snippets.

@vanpariyar
Last active February 18, 2020 08:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vanpariyar/1206af29f562e5e50ca7f9a172f28687 to your computer and use it in GitHub Desktop.
Save vanpariyar/1206af29f562e5e50ca7f9a172f28687 to your computer and use it in GitHub Desktop.
POST THUMBNAIL OR FILE UPLOADING FROM THE FRONT END
/*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