'Wordpress multisite wp_upload_dir wrong

currently i'm trying to upload a Image to a Wordpress-Multisite at server side. (The image is already on another path at the same server)

I've written a small PHP-script which should handle this:

    $upload_dir = wp_upload_dir();
    var_dump( $upload_dir); 
    $filename = basename($imagepath);

    if (wp_mkdir_p($upload_dir['path'])) {
        $file = $upload_dir['path'].'/'.$filename;
    } else {
        $file = $upload_dir['basedir'].'/'.$filename;
    }

    copy($imagepath, $file);
    $wp_filetype = wp_check_filetype($filename, null);
    $attachment = array(
                    'guid' => $upload_dir['url'].'/'.basename($filename),
                    'post_mime_type' => $wp_filetype['type'],
                    'post_title' => sanitize_file_name($filename),
                    'post_content' => '',
                    'post_status' => 'inherit', );

    $attach_id = wp_insert_attachment($attachment, $file, $postid);

Everything works fine, but the image is stored in the wrong folder. wp_upload_dir(); returns the common path /wp-content/uploads/2016/03, not the path for the specific subsite, wich will be /wp-content/uploads/sites/SITE_ID/2016/03

Later when WP uses the image, the url of the image is set to http://example.com/wp-content/uploads/sites/SITE_ID/2016/03/IMAGE.JPG (which is not correct...)

Uploading a file with the built-in media-upload tool from wordpress works correct (files are stored in /wp-content/uploads/sites/SITE_ID/2016/03)

You see, wp_upload_dir() is not working correct..

Thanks..



Solution 1:[1]

A simpler method is to use the switch_to_blog() function

if( is_multisite() ) {
    switch_to_blog( get_current_blog_id() );
      $imgdir = wp_upload_dir();
      // do more process related to current blog
    // close the swicth
    restore_current_blog();
}

See details at https://developer.wordpress.org/reference/functions/switch_to_blog/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nadal