wordpress通过接口实现图片上传

2026年6月5日 飞飞 阅读(13)
知识付费主题,优惠促销中:xx-blog主题

在用wordpress写接口的时候,通常需要通过接口上传图片功能,不仅仅需要能上传,而且要将上传的文件放到媒体库中,这样才能保存下来。

首先我们使用register_rest_route()来注册rest api,我们将代码放到functions.php文件中。

//注册媒体上传端点
register_rest_route(
    'wp/v2', 
    '/upload_file', 
    array(
        'methods' => 'POST',
        'callback' => 'my_custom_upload_handler',
        'permission_callback' => function () { 
              // 确保只有登录用户可以上传 
              return current_user_can( 'upload_files' ); 
         }
    )
);

上面的代码我们指定了一个回调函数,函数名字为:my_custom_upload_handler,那么下面我们就需要写这个回调函数

function my_custom_upload_handler( $request ) {
    // 检查是否有文件上传
    $file = $_FILES['file'];
    if ( empty( $file ) ) {
        return new WP_Error( 'no_file', '未上传任何文件', array( 'status' => 400 ) );
    }

    // 引入处理上传所需的核心文件
    if ( ! function_exists( 'wp_handle_upload' ) ) {
        require_once( ABSPATH . 'wp-admin/includes/file.php' );
    }

    // 配置上传参数(绕过默认的类型检查,通常建议保留,但此处按需配置)
    $upload_overrides = array( 'test_form' => false );

    // 上传到 WordPress 媒体库目录
    $movefile = wp_handle_upload( $file, $upload_overrides );

    if ( $movefile && ! isset( $movefile['error'] ) ) {
        // 准备将文件信息插入媒体库附件表
        $attachment = array(
            'post_mime_type' => $movefile['type'],
            'post_title'     => sanitize_file_name( basename( $movefile['file'] ) ),
            'post_content'   => '',
            'post_status'    => 'inherit'
        );

        // 插入附件表并生成媒体 ID
        require_once( ABSPATH . 'wp-admin/includes/image.php' );
        $attach_id = wp_insert_attachment( $attachment, $movefile['file'] );
        wp_update_attachment_metadata( $attach_id, wp_generate_attachment_metadata( $attach_id, $movefile['file'] ) );

        return rest_ensure_response( array(
            'success'   => true,
            'message'   => '文件上传成功',
            'attachment_id' => $attach_id,
            'file_url'  => $movefile['url']
        ) );
    } else {
        return new WP_Error( 'upload_error', $movefile['error'], array( 'status' => 500 ) );
    }
}

这样我们就实现图片的上传。


关注微信公众号『xx主题网

第一时间了解最新网络动态
关注博主不迷路~

未经允许不得转载:xx主题网 » wordpress通过接口实现图片上传
分享到:

评论抢沙发

要发表评论,您必须先

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏

扫码关注微信公众号

扫描关注xx主题网