使用Wordpress Rest API在页面上上传图像

时间:2018-08-16 06:39:16

标签: wordpress wordpress-rest-api

我想在页面上使用 api 上传图片,所以有人告诉我我该怎么做吗?

现在我使用此api

  

http://localhost/test_project/wp-json/wp/v2/media

但是在页面或帖子上上传图像对我没有帮助。

我使用wordpress json api插件。

1 个答案:

答案 0 :(得分:5)

您可以使用以下代码进行操作。在这里,我使用了wp_handle_upload

       $param = array('search' => 'XXXXXXXX');

        $imagetype = array(
            'bmp'  => 'image/bmp',
            'gif'  => 'image/gif',
            'jpe'  => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'jpg'  => 'image/jpeg',
            'png'  => 'image/png',
            'tif'  => 'image/tiff',
            'tiff' => 'image/tiff'
        );

        $override = array(
            'mimes'     => $imagetype,
            'test_form' => false
        );

        $upload_file = wp_handle_upload( $_FILES['YOUR_UPLOAD_FILE_NAME'], $override );
        remove_filter( 'upload_dir', array($this, 'change_upload_dir') );
        if ( isset( $upload['error'] ) ){
            // DO ACTION ACCORDINGLY
        } else {
            // File is uploaded successfully. 
            $uploaded_file_url = $upload_file['url'];
            $uploaded_file_name = basename($upload_file['url']);
        }