WordPress assign feature image to post from URL/Path programmatically

WordPress how to assign the feature image to the post programmatically from the URL or Path of the image. Many times we need to create the WordPress post programmatically at that time we need to add the feature image to the created the post.

How we can easily set the feature image to the create post. so let’s see, We can create the function for set feature image in the created post like

function thecodingstuff_post_featureimage( $image_url, $post_id  ){
    $uploadDirectory = wp_upload_dir();
    $featureImage = file_get_contents($image_url);
    $filename = basename($image_url);
    if(wp_mkdir_p($uploadDirectory['path'])){
        $file = $uploadDirectory['path'] . '/' . $filename;
    }else{
        $file = $uploadDirectory['basedir'] . '/' . $filename;
    }
    file_put_contents($file, $featureImage);

    $wp_filetype = wp_check_filetype($filename, null );
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => sanitize_file_name($filename),
        'post_content' => '',
        'post_status' => 'inherit'
    );
    $attach_id = wp_insert_attachment( $attachment, $file, $post_id );
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
    $result = wp_update_attachment_metadata( $attach_id, $attach_data );
    $result = set_post_thumbnail( $post_id, $attach_id );
}

Just used thecodingstuff_post_featureimage function and pass the image URL/Path and created post id to the function.

It’s too easy to assign the feature image to the WordPress post by id.

If you face any issue after using this code write the comment below.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s