Skip to content

Instantly share code, notes, and snippets.

@spacedmonkey
Created May 23, 2019 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save spacedmonkey/74e584340c981783d199e7f47ffb875c to your computer and use it in GitHub Desktop.
Save spacedmonkey/74e584340c981783d199e7f47ffb875c to your computer and use it in GitHub Desktop.
Add gutenberg blocks to WordPress API as json.
<?php
add_action( 'rest_api_init', function () {
$types = get_post_types(
[
'show_in_rest' => true,
],
'names'
);
register_rest_field( $types,
'has_blocks',
array(
'get_callback' => function ( $object ) {
return has_blocks( $object['id'] );
},
'update_callback' => null,
'schema' => array(
'description' => __( 'Has blocks.' ),
'type' => 'boolean'
),
)
);
register_rest_field( $types,
'blocks',
array(
'get_callback' => function ( $object ) {
$blocks = parse_blocks( $object['content']['raw'] );
$output = [];
foreach ( $blocks as $block ) {
if ( $block['blockName'] ) {
$block['rendered'] = render_block( $block );
$output[] = $block;
}
}
return $output;
},
'update_callback' => null,
'schema' => array(
'description' => __( 'Blocks.' ),
'type' => 'object'
),
)
);
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment