Wordpress gutenberg按自定义帖子类型获取帖子



我正在获取数据以填充反应古腾堡块中的选择。下面的代码给了我来自Wordpress的帖子。但我想根据自定义帖子类型"df_form"过滤这些帖子。我该怎么做?

/**
* Loading Posts
*/
getOptions() {
let posts = new wp.api.collections.Posts();
return ( posts).fetch().then( ( posts ) => {
if( posts && 0 !== this.state.selectedPost ) {
// If we have a selected Post, find that post and add it.
const post = posts.find( ( item ) => { return item.id == this.state.selectedPost } );
// This is the same as { post: post, posts: posts }
this.setState( { post, posts } );
} else {
this.setState({ posts });
}
});

到目前为止我试过这个,但它没有用:

let posts = wp.data.select('core').getEntityRecords('postType', 'df_form', { per_page: -1 });

从数据存储中检索时,由于某些数据是异步加载的,因此需要等到应用程序状态完全加载。 特别是您调用依赖于 REST API 的数据的情况。您可能需要考虑高阶组件,特别是使用Select或使用Select。

getOptions = withSelect( (select) => { 
return select('core').getEntityRecords('postType', 'df_form', { per_page: -1 });
} )

以下是使用异步数据的文档:https://developer.wordpress.org/block-editor/packages/packages-data/#api

另外,您是否尝试过使用Gutenberg的api-fetch软件包?

apiFetch( { path: '/wp/v2/df_form' } ).then( posts => {
console.log( posts );
} );

以下是文档:https://developer.wordpress.org/block-editor/packages/packages-api-fetch/

最新更新