Search code examples
wordpresswordpress-gutenberg

wp.data.select('core').getPostType('post-type') returns undefined in Gutenberg


I'm building a Wordpress plugin that relies on custom fields being enabled when registering a custom post type. I want to check if the custom-fields key exists (and is true) in supports in the post type object. However, when I call wp.data.select('core').getPostType('post-type'), it returns undefined. If I call it directly from the console, I get the post type object I expect, so I'm not sure why it isn't working in my code.

I've tried calling this from a few places.

E.g. When registering the plugin panel:

// 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: '',
});

or within the plugin itself via 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);

No matter where I call it, the post type object returns undefined.

I'm using the Gutenberg Plugin, version 6.5.0 and WordPress version 5.2.3.

Any help is appreciated.


Solution

  • Calling getCurrentPostType() will return e.g. post. You may not need to wrap it in getPostType too. Also, according to https://github.com/WordPress/gutenberg/issues/13555, you will need to “subscribe” (wp.data.subscribe) as this is an asynchronous call, and so will return null the first time you run it.