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:

Read More
    $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..

Related posts

2 comments

  1. i solved it!

    For everyone with the same problem, the solution is simple:

    1. When you’re on multisite, register a filter for “upload_dir”
    2. define a function, where you change temporarily the paths and urls
    3. That’s it!

      if(is_multisite()){
          add_filter('upload_dir', 'fix_upload_paths');
      }
      
      function fix_upload_paths($data)
      {
          $data['basedir'] = $data['basedir'].'/sites/'.get_current_blog_id();
          $data['path'] = $data['basedir'].$data['subdir'];
          $data['baseurl'] = $data['baseurl'].'/sites/'.get_current_blog_id();
          $data['url'] = $data['baseurl'].$data['subdir'];
      
          return $data;
      }
      

    Hope someone can use it. Hours of hours for me.

Comments are closed.