Skip to content

Instantly share code, notes, and snippets.

@tomjn
Created August 21, 2020 22:30
Show Gist options
  • Save tomjn/2cec90edd650a439d33a1fcf3df53057 to your computer and use it in GitHub Desktop.
Save tomjn/2cec90edd650a439d33a1fcf3df53057 to your computer and use it in GitHub Desktop.
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