Question: How do I extend or override Server Side Rendering?
Answer: Use some PHP code to hook into block registration and override the callback logic.
Implement this in your theme’s functions.php
or in a plugin.
/**
* Hook into register_block_type_args before WP_Block_Supports
*/
add_filter( 'register_block_type_args', 'thisis_register_block_type_args', 9 );
Then in the filter function, replace the callback function for the block with your own.
Repeat this for each block you want to override, changing the block name and the callback function.
$args = thisis_maybe_override_block( $args,'core/navigation-link', 'render_block_core_navigation_link' );
The thisis_maybe_override_block
replaces the render_callback
parameter with your override function. Note: the thisis_
prefix.
function thisis_maybe_override_block($args, $blockname, $render_callback)
{
$sb_render_callback = 'thisis_' . $render_callback;
if ($blockname == $args['name'] && function_exists($sb_render_callback)) {
if ('gutenberg_' . $render_callback == $args['render_callback']) {
$args['render_callback'] = $sb_render_callback;
}
}
return $args;
}
Note: This logic overrides Gutenberg’s server side rendering, not WordPress core.
Code your override function using the same parameters as expected by the Gutenberg block rendering function.
/**
* Overrides core/navigation-link
*
* @param $attributes
* @param $content
* @param $block
* @return string
*/
function thisis_render_block_core_navigation_link($attributes, $content, $block)
{
$attributes = thisis_fiddle_nav_atts($attributes);
$html = gutenberg_render_block_core_navigation_link($attributes, $content, $block);
return $html;
}
The function thisis_fiddle_nav_atts
makes changes to the $attributes
structure. For this theme it replaces a hardcoded URL used in the theme’s development site with site_url
.