正如@Alvero在评论中指出的,现在需要指定wp-api-fetch,而不仅仅是在块注册中提供wp-api。
$index_js = \'sample-post/index.js\';
wp_register_script(
\'sample-post-block-block-editor\',
plugins_url( $index_js, __FILE__ ),
array(
\'wp-blocks\',
\'wp-i18n\',
\'wp-element\',
\'wp-api-fetch\',
),
filemtime( "$dir/$index_js" )
);
然后在您的块中,使用wp调用它。apiFetch函数:
var registerBlockType = wp.blocks.registerBlockType,
el = wp.element.createElement,
__ = wp.i18n.__,
apiFetch = wp.apiFetch;
const postSelections = [];
const allPosts = apiFetch({path: "/wp/v2/featured-post"}).then(fps => {
postSelections.push({label: "Select a Post", value: 0});
$.each( fps, function( key, val ) {
postSelections.push({label: val.title.rendered, value: val.id});
});
return postSelections;
});