I've pulling pulling my hair for the last 2 days with this and searching did not result in any solution to the issue I am having.
I wanted to use <serverSideRender /> to load dynamic content in the front-end as well as see the generated content in the Gutenberg editor. I tested it with the simple example given on the Gutenberg doc page.
Here is the JS code:
const { registerBlockType } = wp.blocks;
const { serverSideRender } = wp.serverSideRender
registerBlockType( 'gutenberg-examples/example-dynamic', {
title: 'Example: last post',
icon: 'megaphone',
category: 'widgets',
edit: function( props ) {
return [
<p>serverSideRender should appear here:</p>,
<serverSideRender
block="gutenberg-examples/example-dynamic"
attributes={ props.attributes }
/>
];
},
} );
PHP Code:
function gutenberg_examples_dynamic_render_callback( $attributes, $content ) {
$recent_posts = wp_get_recent_posts( array(
'numberposts' => 1,
'post_status' => 'publish',
) );
if ( count( $recent_posts ) === 0 ) {
return 'No posts';
}
$post = $recent_posts[ 0 ];
$post_id = $post['ID'];
return sprintf(
'<a class="wp-block-my-plugin-latest-post" href="%1$s">%2$s</a>',
esc_url( get_permalink( $post_id ) ),
esc_html( get_the_title( $post_id ) )
);
}
function gutenberg_examples_dynamic() {
register_block_type( 'gutenberg-examples/example-dynamic', array(
'render_callback' => 'gutenberg_examples_dynamic_render_callback'
) );
}
add_action( 'init', 'gutenberg_examples_dynamic' );
The front-end displays the post as intended. Screenshot below:
But in Gutenberg the block does not show the dynamic content. In theory I should see the same thing as the front-end right? Or am I missing something?
This is what I see in Gutenberg:
As you can see, none of the dynamic content is rendered and there aren't any errors in the console either.
What am I doing wrong? Any help would be much appreciated.
Thanks in advance