I wrote a custom script to insert a post into WordPress and upload 3 images to the WP uploads directory.

To write the post I use the WP function wp_insert_post( $wp_post_array, true );. Inside the script at various stages I also use wp_get_attachment_image_src($image_id, $size)[0];, wp_get_attachment_metadata($image_id); and wp_get_attachment_image( $image_id, 'large', false, $image_attr ); but to upload the images and create their metadata I wrote this custom function below...

I must have messed up somewhere because I get a 500 Connection Timeout error when I run this code (even though it is only 3 images that are less than 1Mb each in size).

Can somebody spot what I am doing wrong? Thank you for your eyes and experience.

function insert_WP_Images_Data( $post_id, $image_url ) {

global $writer_WP_id;

$upload_dir = wp_upload_dir();

if ( isset($image_url) && isset($post_id) ) {

    $filename = basename($image_url);
        $file = $upload_dir['path'] . '/' . $filename;
        $file = $upload_dir['basedir'] . '/' . $filename;
    $image_data = file_get_contents( $image_url );
    file_put_contents($file, $image_data);

    $wp_filetype = wp_check_filetype($filename, null);
    $attachment = array(
    'post_author' => $writer_WP_id,
    'post_content' => '',
    'post_title' => $_SESSION['artist'],
    'post_status' => 'inherit',
    'post_name' => pathinfo($image_url)['filename'],
    'post_mime_type' => $wp_filetype['type'],
    'post_parent' => $post_id,
    'guid' => $upload_dir['url'].'/'.$filename
    //  'post_title' => sanitize_file_name($filename),

    $image_id = wp_insert_attachment( $attachment, $file, $post_id );

    require_once( ABSPATH.'wp-admin/includes/image.php' );
    $attach_data = wp_generate_attachment_metadata( $image_id, $file );
    $res1 = wp_update_attachment_metadata( $image_id, $attach_data );
    $res2 = set_post_thumbnail( $post_id, $image_id );

    return $image_id;
} else {
    echo '<span class="error">No post is selected or image is selected</span>';

I have already tried increasing my server execution time in cPanel (200, 600) and via .htaceess (300) but nothing works...

  • 1
    Can you share some information on how and when this function gets called? The context is important. How come it returns a post ID sometimes, but doesn't return anything at all at other times? What does your PHP error log say? – Tom J Nowell Jun 11 at 14:09
  • I'd also note that some hosts disable downloading via file_get_contents, but you shouldn't need to as there's a dedicated API for downloading things and turning them into attachments. I also notice none of the function calls ever check for error values or failure. If creating the attachment failed with a WP_Error or a false value, that error object gets passed to other functions as a post ID anyway, and there's no check to print out an error or warning if that happens – Tom J Nowell Jun 11 at 15:54

This function is completely unnecessary, and can be replaced with the official WP function called media_sideload_image:

media_sideload_image( string $file, int $post_id, string $desc = null, string $return = 'html' )

for example:

$new_image_id = media_sideload_image(
    "Toms great picture",


Don't forget to check the result, if this fails it will return a WP_Error object, and you must handle it. The error object contains the message telling you what went wrong, and it's why your original code failed mysteriously ( it never checked for errors so if one happened it didn't say anything ).

If you want to use this outside WP Admin, you'll need to include one or two files before using it. Read the official documentation for how to do that

| improve this answer | |
  • Hello @TomJNowell, thank you for your reply. I did not know about media_sideload_imge - are you saying that that function handles the upload as well as generates the thumbnails and the metadata and the relationships/terms in all the DB fields? – marcnyc Jun 11 at 17:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.