如何从自定义Gutenberg块向WordPress数据库上传文件?
自定义Gutenberg文件上传块开发问题
我想创建一个自定义Gutenberg块,包含文件输入框,支持上传任意格式文件并存储到WordPress数据库,最终前端用HTML的<a>标签展示供用户下载。
以下是我的块文件夹内index.js中的演示代码(代码不够规范):
wp.blocks.registerBlockType('sab/upload-block', { title: 'Upload Block', icon: 'lightbulb', category: 'common', attributes: { url: 'string', default: '', }, description: 'Add downloadable files to your post.', example: { attributes: {}}, edit: function (props) { function fileDecoder(identifier) { const input = document.querySelector(`#${identifier}`); const fReader = new FileReader(); fReader.readAsDataURL(input.files[0]); fReader.onloadend = function(event) { setAttribute({url: event.target.result}) } } return ( <> <label>Upload a file</label> <input id='upload-file' type="file" onChange={() => props.fileDecoder('upload-file')} /> </> ) }, save: function () { return null } })
以下是index.php中的代码:
<?php /* Plugin Name: Upload Block Description: Add downloadable files to your post. Version: 1.0 Author: XYZ */ if( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly // file inside my inc folder that creates the markup require_once plugin_dir_path(__FILE__) . 'inc/generateUploadBlockHTML.php'; class UploadBlock { function __construct() { add_action('init', array($this, 'assets')); } function assets() { register_block_type(__DIR__, array( 'render_callback' => array($this, 'theHTML') )); } function theHTML($attributes) { if (isset($attributes)) { // IDEALLY UPLOAD THE FILE HERE SO I CAN JUST USE IT ELSEWHERE, BUT I DO NOT KNOW HOW TO DO IT return <a href="$attributes['data']['url]" download="file"> } else { return NULL; } } } $uploadBlock = new UploadBlock();
我曾尝试仅用JavaScript实现,但认为必须将文件上传至WordPress数据库,才能在其他模板中调用使用。
内容的提问来源于stack exchange,提问作者webcoder
相关产品推荐
相关产品推荐

