Set Featured Image from Front End on WordPress

We can use plugins or we can use custom code on theme file submit post from front end.
I have used plugins such as User Submitted Posts , WP User Frontend etc and also custom code for submitting post.
Many plugins too don’t have settings for featured images. To Create/submit post from theme file on front end we can use following code:

// Create post object
$my_post = array(
'post_title' => 'My post',
'post_content' => 'This is my post.',
'post_status' => 'draft',
'post_type' => 'post', // we can set custom post type too

// Insert the post into the database
$post_ID = wp_insert_post( $my_post );

For more about wp_insert_post follow codex.
And to upload image we can use following image handling code :

require_once (ABSPATH.'/wp-admin/includes/media.php');
require_once (ABSPATH.'/wp-admin/includes/file.php');
require_once (ABSPATH.'/wp-admin/includes/image.php')
$attachmentId = media_handle_upload('async-upload', $post_ID);

For media_handle_upload, get more details from Codex.
And now we can use following code to set image as featured image:

set_post_thumbnail($post_ID, $attachmentId);

In above code, we can add/use many other code for validate error, image etc before making it featured image.
Note: We need to make a post submitting form with image before getting into those code.



1 Comment

  1. kevin says: Reply

    Thanks so much for this vinay – this article really came through for me for a new plugin I was working on with NextGEN Gallery!

Leave a Reply