【问题标题】:upload image with wordpress rest api使用 wordpress rest api 上传图片
【发布时间】:2015-05-09 00:42:12
【问题描述】:

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

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

谢谢

【问题讨论】:

    标签: wordpress wp-api


    【解决方案1】:

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

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

    您可以使用此技巧检索图像 url: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 );
    

    【讨论】:

    • 你能帮我在 Ruby 中做同样的事情吗?
    • Nishant,我没有使用 API 作为答案。不确定 Ruby :)
    • 在其余 api 中,将 image.php 的 include 包含在 function_exists 中。通常这仅包含在管理员中(与前端相比),但我看到它也包含在其余 api 中,因此根据您的使用情况,您可能会遇到错误。 if ( ! function_exists('wp_generate_attachment_metadata') ) { require_once( ABSPATH . 'wp-admin/includes/image.php' ); }
    猜你喜欢
    • 2019-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多