WordPress is a great CMS. It’s easy to set a featured image to the post from admin but it’s panic when we try to upload an image from the front end and trying to set it as a featured image. To allow featured image from the front end, you need to create a front end template, Where you can upload an image and can set it to featured image.
Step 1: Create an upload Image HTML.
Below is the featured image input type. Place it in your code. For the demo, I have used only file type.
<form action="" method="post" enctype="multipart/form-data"> <input type="file" name="FeatureImage"> <input type="submit" name="btnSubmit" value="Submit"> </form>
Step 2: Submit Response.
After implementing the form, We need to get all the form information after submitting the form. Use the below code and merge it with your existing code.
<?php if(is_uploaded_file($_FILES['FeatureImage']['tmp_name'])){ $target_dir =ABSPATH.'/wp-content/uploads/'.date('Y').'/'.date('m').'/'; $date= date('m-d-Y-H-i-s' ); $target_file = $target_dir.$date."-".$_FILES['FeatureImage']['name']; $file_path=$date."-".$_FILES['FeatureImage']['name']; if(move_uploaded_file($_FILES['FeatureImage']['tmp_name'],$target_file)){ $file_path = $date."-".$_FILES['FeatureImage']['name']; } $image_url = $target_file; // Define the image URL here $upload_dir = wp_upload_dir(); // Set upload folder $image_data = file_get_contents($image_url); // Get image data $filename = basename($image_url); // Create image file name $file_without_ext_1 = substr($filename, 0, strrpos(""."", $filename)); if($file_path != ''){ // Check image file type $wp_filetype = wp_check_filetype( $filename, null ); // Set attachment data $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name( $filename ), 'post_content' => '', 'post_status' => 'inherit' ); // Create the attachment $attach_id = wp_insert_attachment( $attachment, $image_url , $post_id ); // Include image.php require_once(ABSPATH . 'wp-admin/includes/image.php'); // Define attachment metadata $attach_data = wp_generate_attachment_metadata( $attach_id, $image_url ); // Assign metadata to attachment wp_update_attachment_metadata( $attach_id, $attach_data ); // And finally assign featured image to post set_post_thumbnail( $post_id, $attach_id ); } } ?>
In the above code, ‘FeatureImage’ is the name of the file input file. Please change it as per your form.