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..
i solved it!
For everyone with the same problem, the solution is simple:
That’s it!
Hope someone can use it. Hours of hours for me.
A simpler method is to use the
switch_to_blog()
functionSee details at https://developer.wordpress.org/reference/functions/switch_to_blog/