我正在尝试使我的块属性显示在REST API中。
首先,我添加了rest_api_init
钩子将我的区块列入白名单。
add_action(
\'rest_api_init\',
function () {
if ( ! function_exists( \'use_block_editor_for_post_type\' ) ) {
require ABSPATH . \'wp-admin/includes/post.php\';
}
// add Location Block to the WordPress REST API
$post_types = get_post_types_by_support( [ \'editor\' ] );
foreach ( $post_types as $post_type ) {
if ( use_block_editor_for_post_type( $post_type ) ) {
register_rest_field(
$post_type,
\'blocks\',
[
\'get_callback\' => function ( array $post ) {
$raw_blocks= parse_blocks( $post[\'content\'][\'raw\'] );
$whitelisted_blocks = [];
foreach ($raw_blocks as $raw_block) {
if( $raw_block[\'blockName\']==\'myplugin/block-map-location\' ){
array_push($whitelisted_blocks, $raw_block);
}
}
return $whitelisted_blocks;
},
]
);
}
}
}
);
这将输出我的原始块内容,但
attrs
数组为空。
blocks:
0:
blockName: "myplugin/block-map-location"
attrs: []
innerBlocks:; []
innerHTML: "\\n<div class=\\"wp-block-myplugin-block-map-location\\" aria-label=\\"Interactive Map\\" role=\\"region\\"><figure><div class=\\"map-pp\\" id=\\"placepress-map\\" data-lat=\\"41.50214445\\" data-lon=\\"-81.6751670486689\\" data-zoom=\\"13\\" data-basemap=\\"carto_voyager\\"></div><figcaption class=\\"map-caption-pp\\">This is the map caption.</figcaption></figure></div>\\n"
innerContent:
0: "\\n<div class=\\"wp-block-myplugin-block-map-location\\" aria-label=\\"Interactive Map\\" role=\\"region\\"><figure><div class=\\"map-pp\\" id=\\"placepress-map\\" data-lat=\\"41.50214445\\" data-lon=\\"-81.6751670486689\\" data-zoom=\\"13\\" data-basemap=\\"carto_voyager\\"></div><figcaption class=\\"map-caption-pp\\">This is the map caption.</figcaption></figure></div>\\n"
为了解决这个问题,我用古腾堡手册中的例子尝试了以下方法,但似乎没有任何效果。(请注意,在本例中,我正在使用自定义的“locations”帖子类型,并试图从我的块中获取“lat”和“lon”属性。)
add_action( \'init\', \'register_block_attributes\' );
function register_block_attributes() {
register_meta( \'post\', \'lat\', array(
\'object_subtype\' => \'locations\',
\'show_in_rest\' => true,
) );
register_meta( \'post\', \'lon\', array(
\'object_subtype\' => \'locations\',
\'show_in_rest\' => true,
) );
}
我显然遗漏了一些东西,但在文档中找不到任何答案。