Skip to content

Instantly share code, notes, and snippets.

@TylerB24890
Last active August 12, 2019 05:36
Show Gist options
  • Save TylerB24890/8ad9c185ff1896e782eabc281f9ec64c to your computer and use it in GitHub Desktop.
Save TylerB24890/8ad9c185ff1896e782eabc281f9ec64c to your computer and use it in GitHub Desktop.
PHP Gutenberg Serializer
<?php
/**
* Serialize Gutenberg Blocks into HTML Markup
*
* @param array $block Array of block data to be serialized
* @return string Gutenberg HTML markup of serialized block
*/
function serialize_block( $block ) {
if ( ! isset( $block['blockName'] ) ) {
return false;
}
$name = $block['blockName'];
if ( 0 === strpos( $name, 'core/' ) ) {
$name = substr( $name, strlen( 'core/' ) );
}
if ( empty( $block['attrs'] ) ) {
$opening_tag_suffix = '';
} else {
$opening_tag_suffix = ' ' . json_encode( $block['attrs'] );
}
if ( empty( $block['innerHTML'] ) ) {
return sprintf(
'<!-- wp:%s%s /-->',
$name,
$opening_tag_suffix
);
} else {
return sprintf(
'<!-- wp:%1$s%2$s -->%3$s<!-- /wp:%1$s -->',
$name,
$opening_tag_suffix,
$block['innerHTML']
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment