I’m trying to build a custom Gutenberg Block, which will be rendered dynamically (from PHP).
I’ve spent a significant amount of time searching for different solutions, minimized my code to the absolutely necessary, and still it doesnt work.
My main reference is this page: https://developer.wordpress.org/block-editor/tutorials/block-tutorial/creating-dynamic-blocks/
And here’s my code:
PHP (functions.php):
function register_test_block(){
wp_register_script('test-block',
get_template_directory_uri().'/js/test-block.js',
array('wp-blocks') );
register_block_type('test/testblock', array(
'render_callback' => function( $block_attributes, $content ) {
return '<p>OMG SUCCESS!</p>';
},
'editor_script' => 'test-block' )
);
}
add_action('init', 'register_test_block');
test-block.js:
const { registerBlockType } = wp.blocks;
registerBlockType('test/testblock', {
title: 'test block',
edit: props => {
return (<p>test</p>);
},
save: props => {
return null;
}
});
i really have no idea why this isn’t working as its supposed to, on the frontend the block is just not rendered at all, not even a comment or anything. Oh and my current WP Version is 5.5.3 with PHP 7.3 if this helps..
Does anyone know why my block isn’t rendering? Thanks!
2
Answers
Really appreciate your help S.Walsh! Cleaning the browsercache or reentering the block didn't really help. Then I rearranged some files, changed some function names, and suddenly it works. Here's my current js (if someone gets the same problem):
and this is the php part:
Your code is on the right path as you do need to register the block both in JavaScript and PHP. The missing link to make it work is that in the JavaScript edit() function, the actual rendering of the PHP callback function is done via
<ServerSideRender>
component, eg:test-block.js:
functions.php
There are many more useful attributes that are part of the ServerSideRender component for building dynamic blocks, however: its a legacy component and if you are building a new data-driven block for Gutenberg, it would be best to see if you are able to achieve your goals via the REST API endpoints where possible.