1

我在使用 WordPress REST API (WP-API) 上传图像时遇到问题。有人可以提供一些示例代码。基本上,我有一张从服务中获得的图像,并且显示在<img>标签中。现在我需要获取该图像并使用 javascript 将其保存在媒体库中。

或者(不使用 WP-API)如果有一个插件可以做到这一点,我可以传递要获取的图像的 url 保存在媒体库中。

谢谢

4

1 回答 1

0

您可以使用wp_insert_attachmentif API 不是首选。资源

$parent_post_id如果媒体库不是特定于帖子的,请忽略。

您可以使用以下技巧检索图像 url:检索图像,然后使用变量$filename

// $filename should be the path to a file in the upload directory.
$filename = '/path/to/uploads/2013/03/filename.jpg';

// The ID of the post this attachment is for.
$parent_post_id = 37;

// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( basename( $filename ), null );

// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();

// Prepare an array of post data for the attachment.
$attachment = array(
 'guid'           => $wp_upload_dir['url'] . '/' . basename( $filename ), 
 'post_mime_type' => $filetype['type'],
 'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
 'post_content'   => '',
 'post_status'    => 'inherit'
);

// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );

// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . 'wp-admin/includes/image.php' );

// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
于 2015-05-09T00:58:00.180 回答