Skip to content

Instantly share code, notes, and snippets.

@tomjn
Created Aug 21, 2020
Embed
What would you like to do?
A basic server rendered block, like a shortcode but blocks!
( function( wp ) {
var el = wp.element.createElement;
wp.blocks.registerBlockType( 'tomjn/dynamic', {
title: 'Toms Dynamic Block',
edit: function( props ) {
return el( wp.serverSideRender, {
block: 'tomjn/dynamic',
attributes: props.attributes,
} );
},
} );
}( window.wp ));
<?php
/**
* Plugin Name: Server Rendered Block Example
* Description: Like a shortcode but it's a block!
*/
function render_toms_block( array $attributes, $content ) : string {
return "Hello World!";
}
function register_toms_block() {
// Register the JS.
wp_register_script(
'toms-block-js',
plugins_url( 'block.js', __FILE__ ),
[ 'wp-blocks', 'wp-element' ]
);
// Register the block.
register_block_type(
'tomjn/dynamic',
[
'editor_script' => 'toms-block-js',
'render_callback' => 'render_toms_block',
]
);
}
add_action( 'init', 'register_toms_block' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment