繁体   English   中英

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

[英]Wordpress gutenberg fetch posts by custom post type

我正在获取数据以在反应古腾堡块中填充 select。 下面的代码给了我来自 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 });

由于某些数据正在异步加载而从数据存储中检索时,您需要等到应用程序 state 完全加载。 特别是。 您需要依赖 REST API 的数据的情况。 您可能需要考虑高阶组件,特别是 withSelect 或 useSelect。

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

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

另外,您是否尝试过使用古腾堡的 api-fetch package?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM