用wordpress rest api上传图片

时间:2015-05-09 00:42:13

标签: wordpress wp-api

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

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

由于

1 个答案:

答案 0 :(得分:0)

如果不首选API,您可以使用wp_insert_attachmentSource

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

您可以使用此技巧检索图片网址:Retrieve images,然后将变量用于$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 );