Created
May 23, 2019 14:18
-
-
Save spacedmonkey/74e584340c981783d199e7f47ffb875c to your computer and use it in GitHub Desktop.
Add gutenberg blocks to WordPress API as json.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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