How to save image as featured image in WordPress

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

If you want to save the image as featured image from front end form. Here is the code for making the image as featured image for a particular post.

$filename = $_FILES[‘attachmentfile’][‘name’];
$wp_filetype = wp_check_filetype(basename($filename), null );
if(($wp_filetype[‘ext’] == ‘jpg’) || ($wp_filetype[‘ext’] == ‘jpeg’) || ($wp_filetype[‘ext’] == ‘png’) || ($wp_filetype[‘ext’] == ‘gif’)){
// $filename should be the path to a file in the upload directory.

$uploaddir1 = ‘./wp-content/uploads/’.date(‘Y’).’/’.date(‘m’).’/’;
$uploadfile1 = $uploaddir1 . basename($_FILES[‘attachmentfile’][‘name’]);
move_uploaded_file($_FILES[‘attachmentfile’][‘tmp_name’], $uploadfile1);
$filename1 = $uploadfile1;
$site_url = site_url() . ‘/’;
$imagePathForEmail = str_replace(“./”,$site_url,$uploadfile1);
// The ID of the post this attachment is for.
$parent_post_id = $postr->ID;

// Check the type of file. We’ll use this as the ‘post_mime_type’.
$filetype = wp_check_filetype( basename( $filename1 ), null );

// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();

// Prepare an array of post data for the attachment.
$attachment = array(
‘guid’ => $wp_upload_dir[‘url’] . ‘/’ . basename( $filename1 ),
‘post_mime_type’ => $filetype[‘type’],
‘post_title’ => preg_replace( ‘/\.[^.]+$/’, ”, basename( $filename1 ) ),
‘post_content’ => ”,
‘post_status’ => ‘inherit’
);

// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $filename1, $parent_post_id );

// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . ‘wp-admin/includes/image.php’ );

// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename1 );
wp_update_attachment_metadata( $attach_id, $attach_data );

set_post_thumbnail( $parent_post_id, $attach_id );
}