I've Created a Script that Grabs an image from an external site and it is imported to the WordPress image gallery. -> wp-admin/upload.php [Media Library]

Media Gallery

The Product itself

My Code Snipplet

foreach($url as $linkurl) {
    $tmp = download_url( $linkurl);

    preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $linkurl, $matches);

$clean = str_replace(array("%2B", "%52", "%20", "%5"), "B", basename($matches[0]));

$file_array = array(
    'name' => basename( $clean ),
    'tmp_name' => $tmp

if ( is_wp_error( $tmp ) ) {
    @unlink( $file_array[ 'tmp_name' ] );
    return $tmp;

$id = media_handle_sideload( $file_array, $post_id, 'gallery desc' );

$value = wp_get_attachment_url( $id );

update_post_meta($post_id,  array_push($post_id, '_product_image_gallery', $id));

//update_post_meta($post_id,  array_push($post_id, '_product_image_gallery', $value ));


What am I doing Wrong


1 Answer 1


I think that you have made a mistake in the last line. array_push is not doing what you are trying to achieve (check the Manual) same as update_post_meta accepts different arguments.

Besides that WooCommerce is storing galleries in simple comma separated list like 1,45,78,34 so you should change the last line
update_post_meta($post_id, array_push($post_id, '_product_image_gallery', $id));
update_post_meta($post_id, '_product_image_gallery', $id);
or if you add multiple images then instead of $id enter comma separated list.

  • update_post_meta($post_id, '_product_image_gallery', $id); I tried that now, does not seem like its attaching to the posts.
    – Chen Chiu
    Nov 16, 2015 at 0:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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