简体   繁体   English

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

[英]Wordpress gutenberg fetch posts by custom post type

I am tying to fetch data to populate a select in a react gutenberg block.我正在获取数据以在反应古腾堡块中填充 select。 The code below gives me the posts from Wordpress.下面的代码给了我来自 Wordpress 的帖子。 But I would like to filter these posts on a custom post type 'df_form'.但我想在自定义帖子类型“df_form”上过滤这些帖子。 How would I do that?我该怎么做?

/**
 * 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 });
        }
    });

I tried this so far, but it didn't work:到目前为止,我尝试了这个,但是没有用:

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

When retrieving from the data store because some of the data is being loaded async, you need to wait until the application state is fully loaded.由于某些数据正在异步加载而从数据存储中检索时,您需要等到应用程序 state 完全加载。 Esp.特别是。 your circumstance where you are calling for data that relies on the REST API.您需要依赖 REST API 的数据的情况。 You may want to think about Higher Order Components, specifically withSelect or useSelect.您可能需要考虑高阶组件,特别是 withSelect 或 useSelect。

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

Here is the documentation for working with async data: https://developer.wordpress.org/block-editor/packages/packages-data/#api以下是处理异步数据的文档: https://developer.wordpress.org/block-editor/packages/packages-data/#api

Also, Have you tried using Gutenberg's api-fetch package?另外,您是否尝试过使用古腾堡的 api-fetch package?

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

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

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

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