【发布时间】:2021-05-06 10:32:30
【问题描述】:
我需要使用驱动器上图像的位置将图像上传到 wordpress,如下所示:
“C:\Users\me\Pictures\1.jpg”
不使用文件对话框来选择图像文件,因为我需要使用 url 上传图像及其在驱动器上的位置
如何修改下面的代码来做我需要的事情
<?php
require('../wp-load.php');
require_once('../wp-admin/includes/image.php');
//==========================================
echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<p>
<label for="img_url">img_url</label>
<input type="text" name="img_url" id="img_url" />
</p>
<p>
<input type="submit" name="submit" id="submit" value="Submit" />
</p>
</form>
</body>
</html>';
//==========================================
if (isset($_POST["submit"])) {
$image_url = $_POST["img_url"];
$upload_dir = wp_upload_dir();
$image_data = file_get_contents( $image_url );
$filename = basename( $image_url );
if ( wp_mkdir_p( $upload_dir['path'] ) ) {
$file = $upload_dir['path'] . '/' . $filename;
}
else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
file_put_contents( $file, $image_data );
$wp_filetype = wp_check_filetype( $filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name( $filename ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $file );
ECHO $img_url = wp_get_attachment_url($attach_id);
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
?>
【问题讨论】:
标签: php wordpress file-upload