php Gutenberg Shortcode Block with Live Preview

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php Gutenberg Shortcode Block with Live Preview相关的知识,希望对你有一定的参考价值。

var el = wp.element.createElement,
	registerBlockType = wp.blocks.registerBlockType,
	InspectorControls = wp.blocks.InspectorControls,
	TextControl = wp.components.TextControl,
	ServerSideRender = wp.components.ServerSideRender;

registerBlockType( 'jd/shortcode', {
	title: 'JD Shortcode Preview',
	icon: 'shortcode',
	category: 'common',
  
	attributes: {
		shortcode: {
			type: 'string',
			default: '',
		},
	},  

	edit: function( props ) {
		
		return [
			props.isSelected &&
			el(InspectorControls, { key: "inspector"},
				el('h2', {}, 'Shortcode Settings'),
				el(TextControl, {
					label: __( 'Shortcode' ),
					value: props.attributes.shortcode,
					onChange: function(value) { props.setAttribute( { shortcode: value } ); }
				}),
			),
      
			// ensure the block attributes matches this plugin's name
			el(ServerSideRender, {
				key: "editable",
				block: "jd/shortcode",
				attributes:  props.attributes
			})
		];
	},

	save: function() {
		// Rendering in PHP
		return null;
	},
} );
<?php
/**
 * Plugin Name: JD Gutenberg Shortcode Preview
 * Description: Live shortcode previews in Gutenberg
 * Author: johndyer
 * Version: 1.0.0
 *
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// make the script visible to Guteberg
function jd_editor_assets() {
	wp_enqueue_script(
		'jd-shortcode-js', // Handle.
		plugins_url( 'block.js', dirname( __FILE__ ) ), // Block.build.js: We register the block here. Built with Webpack.
		array( 'wp-blocks', 'wp-i18n', 'wp-element' ) // Dependencies, defined above.
	);
}
add_action( 'enqueue_block_editor_assets', 'jd_editor_assets' );


// render callbacks
function jd_do_shortcode( $attributes ) {
	$html = 'No shortcode provided';

	if (!empty($attributes["shortcode"])) {
		$html = do_shortcode( $attributes["shortcode"]);
	}

	return $html;
}

// ServerSideRender callback
function jd_load_blocks() {

	register_block_type( 'jd/shortcode', array(
		'render_callback' => 'jd_do_shortcode',
		'attributes'      => array(
			'shortcode' => array(
				'type'    => 'string',				
			),
		)
	) );	
}
add_action( 'init', 'jd_load_blocks' );

function jd_sample_shortcode($attributes) {
	return 'It works: ' . $attributes['something'];
}

add_shortcode( 'jd_sample_shortcode', 'jd_sample_shortcode' );

以上是关于php Gutenberg Shortcode Block with Live Preview的主要内容,如果未能解决你的问题,请参考以下文章

php 在一行PHP中禁用Gutenberg编辑器

php SHORTCODE:将“类型”字段修剪为“字数”

php 媒体查询ShortCode

php WP Shortcode加载远程内容

php 如何在Blooming中启用Shortcode

php semplice shortcode con contenuto