首页 > 解决方案 > wp.​​data.select('core').getPostType('post-type') 在 Gutenberg 中返回 undefined

问题描述

我正在构建一个 Wordpress 插件,该插件依赖于在注册自定义帖子类型时启用的自定义字段。我想检查帖子类型对象中是否custom-fields存在(并且是true)密钥。supports但是,当我调用时wp.data.select('core').getPostType('post-type'),它会返回undefined。如果我直接从控制台调用它,我会得到我期望的帖子类型对象,所以我不确定为什么它在我的代码中不起作用。

我试过从几个地方打电话给这个。

例如注册插件面板时:

// Loading `wp.editPosts`, `wp.plugins`, etc. excluded for brevity.

const Component = () => {
    const postType = wp.data.select('core/editor').getCurrentPostType();
    const postTypeObj = wp.data.select('core').getPostType(postType);

    if (postTypeObj.supports.hasOwnProperty('custom-fields')) {
        return (
            <PluginDocumentSettingPanel
                name="my-plugin-name"
                title={ __('My Plugin Title', 'pb') }
            >
                <MyPlugin/>
            </PluginDocumentSettingPanel>
        );
    }

    return;
};

registerPlugin('my-plugin-name', {
    render: Component,
    icon: '',
});

或在插件本身内通过withSelect

// Loading `wp.compose`, `wp.data`, etc. excluded for brevity.

class MyPlugin extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            // I'll do something with this later on
            postTypeObj: props.postTypeObj,
        };
    }

    render() {
        return (
            <div></div>
        );
    }
}

export default compose([
    withSelect(select => {
        const {
            getCurrentPostType,
        } = select('core/editor');

        const {
            getPostType,
        } = select('core');

        return {
            postTypeObj: getPostType(getCurrentPostType()),
        }
    }),
])(MyPlugin);

无论我在哪里调用它,post 类型对象都会返回undefined.

我正在使用 Gutenberg 插件、版本6.5.0和 WordPress 版本5.2.3

任何帮助表示赞赏。

标签: wordpresswordpress-gutenberg

解决方案


调用getCurrentPostType()将返回例如post。你可能也不需要把它包起来getPostType。此外,根据https://github.com/WordPress/gutenberg/issues/13555,您将需要“订阅”(wp.data.subscribe),因为这是一个异步调用,因此在您第一次运行它时将返回 null。


推荐阅读