skip to Main Content
WordPress Assign Feature Image To Post From URL/Path Programmatically

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);
        $file = $uploadDirectory['path'] . '/' . $filename;
        $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.


I am a web designer and developer part-time blogger. Write something on some free time. Find my every day thought here :)

Leave a Reply

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

Back To Top