我最终在自定义端点中使用了来自wp media端点的代码,而没有保存post部分。
以下是关于2017年儿童主题的完整示例,以防有人需要。
将此添加到函数中。php
$Custom_Media_Uploader = new Custom_Media_Uploader();
$Custom_Media_Uploader->init();
class Custom_Media_Uploader {
function init() {
add_action( \'rest_api_init\', [ $this, \'register_routes\' ] );
}
function register_routes() {
$version = \'1\';
$namespace = \'custom-end-point/v\' . $version;
$base = \'media\';
register_rest_route( $namespace, \'/\' . $base, array(
[
\'methods\' => WP_REST_Server::CREATABLE,
\'callback\' => [ $this, \'upload_file\' ],
\'permission_callback\' => [ $this, \'file_upload_permissions\'
],
\'args\' => [],
]
) );
}
function file_upload_permissions() {
return is_user_logged_in();
}
function upload_file( $request ) {
$params = $request->get_params();
if ( ! empty( $request[\'post\'] ) && in_array( get_post_type( $request[\'post\'] ), array(
\'revision\',
\'attachment\'
), true )
) {
return new WP_Error( \'rest_invalid_param\', __( \'Invalid parent type.\' ), array( \'status\' => 400 ) );
}
// Get the file via $_FILES or raw data.
$files = $request->get_file_params();
$headers = $request->get_headers();
if ( ! empty( $files ) ) {
$file = $this->upload_from_file( $files, $headers );
} else {
$file = $this->upload_from_data( $request->get_body(), $headers );
}
if ( is_wp_error( $file ) ) {
return $file;
}
$name = basename( $file[\'file\'] );
$name_parts = pathinfo( $name );
$name = trim( substr( $name, 0, - ( 1 + strlen( $name_parts[\'extension\'] ) ) ) );
$url = $file[\'url\'];
$type = $file[\'type\'];
$file = $file[\'file\'];
return [ \'url\' => $url, \'type\' => $type ];
}
/**
* Handles an upload via multipart/form-data ($_FILES).
*
* @since 4.7.0
*
* @param array $files Data from the `$_FILES` superglobal.
* @param array $headers HTTP headers from the request.
*
* @return array|WP_Error Data from wp_handle_upload().
*/
protected function upload_from_file( $files, $headers ) {
if ( empty( $files ) ) {
return new WP_Error( \'rest_upload_no_data\', __( \'No data supplied.\' ), array( \'status\' => 400 ) );
}
// Verify hash, if given.
if ( ! empty( $headers[\'content_md5\'] ) ) {
$content_md5 = array_shift( $headers[\'content_md5\'] );
$expected = trim( $content_md5 );
$actual = md5_file( $files[\'file\'][\'tmp_name\'] );
if ( $expected !== $actual ) {
return new WP_Error( \'rest_upload_hash_mismatch\', __( \'Content hash did not match expected.\' ), array( \'status\' => 412 ) );
}
}
// Pass off to WP to handle the actual upload.
$overrides = array(
\'test_form\' => false,
);
// Bypasses is_uploaded_file() when running unit tests.
if ( defined( \'DIR_TESTDATA\' ) && DIR_TESTDATA ) {
$overrides[\'action\'] = \'wp_handle_mock_upload\';
}
/** Include admin functions to get access to wp_handle_upload() */
require_once ABSPATH . \'wp-admin/includes/admin.php\';
$file = wp_handle_upload( $files[\'file\'], $overrides );
if ( isset( $file[\'error\'] ) ) {
return new WP_Error( \'rest_upload_unknown_error\', $file[\'error\'], array( \'status\' => 500 ) );
}
return $file;
}
}
在主题的根目录下创建一个名为page upload的文件。php
<?php get_header(); ?>
<div class="wrap">
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<input type=\'file\' onchange="uploadFile(this);"/>
<div style="display:none" id="ajax-response">
<div><b>File URL: </b><span id="file-url"></span></div>
<div><b>File type: </b><span id="file-type"></span></div>
<div></div>
</div>
</main><!-- #main -->
</div><!-- #primary -->
</div><!-- .wrap -->
<script>
function uploadFile(input) {
if (input.files && input.files[0]) {
var file = input.files[0];
var formData = new FormData();
formData.append(\'file\', file);
// Fire the request.
jQuery.ajax({
url: \'<?php echo esc_url_raw( rest_url() ) ?>custom-end-point/v1/media\',
method: \'POST\',
processData: false,
contentType: false,
beforeSend: function (xhr) {
xhr.setRequestHeader(\'X-WP-Nonce\', \'<?php echo wp_create_nonce( \'wp_rest\' ) ?>\');
},
data: formData
}).success(function (response) {
jQuery(\'#file-url\').text(response.url);
jQuery(\'#file-type\').text(response.type);
jQuery(\'#ajax-response\').show();
console.log(response);
}).error(function (response) {
console.log(response);
});
}
}
</script>
<?php get_footer();
创建并保存标题为“upload”的页面,然后导航到www.domain。com/upload,上传文件,您可以在上传文件后从媒体端点查看返回的URL和文件类型。
确保您已登录,并且将永久链接设置为post name,以允许端点正常工作。