Reputation: 159
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..
Upvotes: 1
Views: 3566
Reputation: 105
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/
Upvotes: 0
Reputation: 159
i solved it!
For everyone with the same problem, the solution is simple:
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.
Upvotes: 11