如何将已有的ShortCode转换为可一键调用的Gutenberg Block?
实现步骤
1. 先修改原有短代码,兼容自闭合格式
原有短代码仅支持闭合格式的内容参数,调整后可同时支持[video="xxx"]的自闭合写法,适配你需要的两种调用格式:
function video( $atts, $content = null ) { // 兼容自闭合格式的videoID参数 $atts = shortcode_atts( [ 'default' => '', ], $atts ); $video_id = $content ? $content : $atts['default']; if ( empty( $video_id ) ) return ''; // 增加参数转义提升安全性 return '<div class="videoWrapper"><iframe width="1280" height="720" src="https://www.youtube.com/embed/' . esc_attr( $video_id ) . '" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>'; } add_shortcode( 'video', 'video' );
2. 注册自定义古腾堡区块
我们直接注册最简动态块,后台仅需输入视频ID即可,无需手动输入方括号:
2.1 在functions.php中添加区块注册代码
function custom_video_block_register() { // 加载块编辑器所需脚本 wp_enqueue_script( 'custom-video-block', // 请替换为你主题内对应JS文件的实际存放路径 get_template_directory_uri() . '/assets/js/video-block.js', array( 'wp-blocks', 'wp-element', 'wp-components', 'wp-editor' ), filemtime( get_template_directory() . '/assets/js/video-block.js' ) ); // 注册动态块 register_block_type( 'custom/video-block', array( 'editor_script' => 'custom-video-block', 'render_callback' => function( $attributes ) { if ( empty( $attributes['videoId'] ) ) return ''; // 直接调用已有短代码逻辑输出内容 return video( [], $attributes['videoId'] ); }, ) ); } add_action( 'init', 'custom_video_block_register' );
2.2 创建对应JS文件
在你主题对应路径下新建/assets/js/video-block.js,写入以下内容:
const { __ } = wp.i18n; const { registerBlockType } = wp.blocks; const { TextControl } = wp.components; const { InspectorControls, useBlockProps } = wp.blockEditor; registerBlockType( 'custom/video-block', { title: __( '自定义视频块' ), icon: 'video-alt3', category: 'common', attributes: { videoId: { type: 'string', default: '', }, }, edit: ( { attributes, setAttributes } ) => { const blockProps = useBlockProps(); return ( <div { ...blockProps }> <InspectorControls> <TextControl label={ __( 'YouTube视频ID' ) } value={ attributes.videoId } onChange={ ( val ) => setAttributes( { videoId: val } ) } placeholder="请输入YouTube视频ID" /> </InspectorControls> { attributes.videoId ? ( <p>当前已插入视频ID:{ attributes.videoId }</p> ) : ( <p>请在右侧设置栏输入YouTube视频ID</p> ) } </div> ); }, // 动态块前端输出由PHP处理,save方法返回null即可 save: () => null, } );
3. 使用方法
编辑文章时直接在区块库搜索「自定义视频块」点击插入,在右侧设置栏输入对应YouTube视频ID即可,全程无需手动输入[]符号,前端会自动输出你需要的视频渲染内容。
如果仅需要插入短代码文本而非动态渲染,把上面JS的save方法替换为以下内容,同时删除注册块时的render_callback参数即可:
save: ( { attributes } ) => { return attributes.videoId ? `[video]${attributes.videoId}[/video]` : ''; }
内容的提问来源于stack exchange,提问作者jojoreni
相关产品推荐
相关产品推荐

