Skip to content

Instantly share code, notes, and snippets.

@Shelob9
Last active January 17, 2023 22:32
  • Star 22 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Example Gutenberg block with server-side rendering. Gutenberg edit() block creates interface. Gutenberg saves settings automatically, the PHP function passed as `render_callback` to `register_block_type` is used to create HTML for front-end rendering of block.
const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
const el = wp.element.createElement;
registerBlockType( 'hiRoy/serverSide', {
title: __( 'Server Side Block', 'text-domain' ),
icon: 'networking',
category: 'common',
attributes: {
images : {
default: [],
type: 'array',
}
},
edit({attributes, setAttributes, className, focus, id}) {
//Put a user interface here.
},
save({attributes, className}) {
//gutenberg will save attributes we can use in server-side callback
return null;
},
} );
<?php
register_block_type('hiRoy/serverSide', array(
'render_callback' => 'hi_roy_render_callback',
'attributes' => array(
'images' => array(
'type' => 'array'
)
)
)
);
function hi_roy_render_callback( $attributes ){
$images = $attributes[ 'images' ];
return '<div><!-- put image gallery here--></div>';
}
@wpexplorer
Copy link

@bizm - This gist isn't intended to explain how to register blocks it's just an example showing how to use the render_callback argument. Now, you don't actually have to use wp_enqueue_script to load your block JS file - you can and probably should be loading the file via your block.json file, see here: https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/ and scroll down to "Editor Script".

@Shelob9
Copy link
Author

Shelob9 commented Feb 16, 2022

@bizm Here is a more up to date example of how to set up a server-side rendered block: https://github.com/imaginarymachines/everything-all-of-the-time/blob/main/blocks/php-block/init.php

Two issues with your snippet that need corrected:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment