Insert an image into a post by API

You can set the uploaded image as the post thumbnail via,

update_post_meta($post_id,'_thumbnail_id',$attach_id);

Example…

if ($_FILES) {
    foreach ($_FILES as $file => $array) {
        if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
            return "upload error : " . $_FILES[$file]['error'];
        }
        $attach_id = media_handle_upload( $file, $post_id );
    }   
}

update_post_meta($post_id,'_thumbnail_id',$attach_id);

If you are uploading an array of images, then you might wish to specify which image by referencing the key,

$file[0] //for the first image in the array
$file[1] //for the second image in the array
$file[2] //for the third image in the array
etc...

…but that should not be necessary when uploading a single image.

Update:

Based on your comments, if you want to insert the image at the beggining of or before your post content its probably best you filter the the_content function like so,

add_filter( 'the_content', 'insert_img_to_post', 20 );

function insert_img_to_post( $content ) {

    global $post;
    $post_id = $post->ID;

    if ( is_single() )

        $content = sprintf(
            '<img class="post-icon" src="%s" alt="Post icon" title=""/>',
            wp_get_attachment_url(get_post_meta( $post_id, '_thumbnail_id', true )),
            $content
        );

    return $content;
}

…add this function as a separate function/filter in your functions.php file. Do not try and bundle it within your wp_insert_post function as it will not work. This is intended to run by itself, hooking onto the_content filter, inserting the image at the top of the post before the content, then appending the content beneath it.

This is currently running on a single post page (is_single) if you want it to run on something else, like a page, then change to is_page or any other conditional tag that meets your needs.

Leave a Comment