PHP Script to Add Featured Image To Post

PHP Script to Add Featured Image To Post
Like Tweet Pin it Share Share Email

[myad1] It’s easy to upload featured images from the WordPress backend for any type of post from the WordPress admin. On the front end, you need to develop a custom template or have to install a plugin which allows you to upload the featured image.

If you are trying to upload featured image to the post using the custom template then please use below code.

    $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'];
    $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. See the below example to see the form HTML.

<form action="" method="post" enctype="multipart/form-data">
	<input type="file" name="FeatureImage">
	<input type="submit" name="btnSubmit" value="Submit">



Thanks for reading our article. What Next?

Comments (0)

Leave a Reply

Your email address will not be published. Required fields are marked *

5 − three =