直接从 URL 将图像复制到我的服务器并将其上传到 Wordpress 上传文件夹?

vin*_*vin 3 php wordpress file-upload image

我正在尝试通过 PHP 脚本上传图像,如下所述。我正在从 URL 获取图像; 我已经参考了这篇文章实际上,就我而言,我想将其上传到 WordPress 上传文件夹,其中帖子图像被上传,并且您知道 WordPress 在运行时在“wp-content/uploads/”内创建文件夹,并在那里上传图像。所以路径($save_path)不是在运行时决定的。

$url="http://www.google.co.in/intl/en_com/images/srpr/logo1w.png";
$contents=file_get_contents($url);
$save_path="/path/to/the/dir/and/image.jpg";
file_put_contents($save_path,$contents);
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用 WordPress 函数“media_handle_upload”来上传图像而不是“file_put_contents”,但我不知道如何在获取文件内容($contents=file_get_contents($url);)后将文件对象传递给此函数。请协助。

$attachment_id = media_handle_upload( 'my_image_upload', $_POST['post_id'] );
Run Code Online (Sandbox Code Playgroud)

小智 5

100% 运行此代码:

include_once( ABSPATH . 'wp-admin/includes/image.php' );
$imageurl = '<IMAGE URL>';
$imagetype = end(explode('/', getimagesize($imageurl)['mime']));
$uniq_name = date('dmY').''.(int) microtime(true); 
$filename = $uniq_name.'.'.$imagetype;

$uploaddir = wp_upload_dir();
$uploadfile = $uploaddir['path'] . '/' . $filename;
$contents= file_get_contents($imageurl);
$savefile = fopen($uploadfile, 'w');
fwrite($savefile, $contents);
fclose($savefile);

$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
    'post_mime_type' => $wp_filetype['type'],
    'post_title' => $filename,
    'post_content' => '',
    'post_status' => 'inherit'
);

$attach_id = wp_insert_attachment( $attachment, $uploadfile );
$imagenew = get_post( $attach_id );
$fullsizepath = get_attached_file( $imagenew->ID );
$attach_data = wp_generate_attachment_metadata( $attach_id, $fullsizepath );
wp_update_attachment_metadata( $attach_id, $attach_data ); 

echo $attach_id;
Run Code Online (Sandbox Code Playgroud)