簡體   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