我在服务器上有一个图像文件(例如:images / flower.jpg)。 我想通过php文件将此文件添加到媒体库。
我在网上研究了很多,发现下面的代码。此代码需要将html表单上传到媒体库。我必须选择文件并单击上传按钮。我想做的是给一个文件名在php文件中上传,而不是使用html表格。
<?php
include "../wp-config.php";
?>
<form id="file_upload" method="post" action="#" enctype="multipart/form-data">
<input type="file" name="my_file_upload[]" multiple="multiple">
<input name="my_file_upload" type="submit" value="Upload" />
</form>
<?
require_once( '../wp-admin/includes/image.php' );
require_once( '../wp-admin/includes/file.php' );
require_once( '../wp-admin/includes/media.php' );
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$files = $_FILES["my_file_upload"];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array("upload_file" => $file);
$attachment_id = media_handle_upload("upload_file", 0);
if (is_wp_error($attachment_id)) {
// There was an error uploading the image.
echo "Error adding file";
} else {
// The image was uploaded successfully!
echo "File added successfully with ID: " . $attachment_id . "<br>";
echo wp_get_attachment_image($attachment_id, array(800, 600)) . "<br>"; //Display the uploaded image with a size you wish. In this case it is 800x600
}
}
}
}
?>
&#13;