Skip to content

Instantly share code, notes, and snippets.

@junaidbhura
Last active January 14, 2020 04:37
Show Gist options
  • Save junaidbhura/574bc9a7ebae62816121ed7334620fde to your computer and use it in GitHub Desktop.
Save junaidbhura/574bc9a7ebae62816121ed7334620fde to your computer and use it in GitHub Desktop.
<?php
/**
* Serialize an array into a Gutenberg block.
*
* @param array $block Block.
* @return bool|string
*/
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 = ' ' . wp_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,
"\n" . $block['innerHTML'] . "\n"
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment