Is there a way to refresh the category list that is used in a custom component if a user adds a new category using the editor itself? Is there a way to refresh the category list that is used in a custom component if a user adds a new category using the editor itself? wordpress wordpress

Is there a way to refresh the category list that is used in a custom component if a user adds a new category using the editor itself?


You can use the useSelect custom React hook within a function component. useSelect will "subscribe" to changes and automatically re-render the component if the values change (i.e. the user selects another category).

The component to create a <SelectControl> that lets the user select a "Primary Category" could look something like this:

/** * WordPress dependencies */import { __ } from '@wordpress/i18n';import { SelectControl } from '@wordpress/components';import { useSelect } from '@wordpress/data';import { useEntityProp } from '@wordpress/core-data';function PostPrimaryCategory() {    const categories = useSelect((select) => {        /**         * Get the currently selected categories for a post. Since we are using          * useSelect, this will get updated any time the user adds or removes a          * category from the post.         */        const catIds = select('core/editor').getEditedPostAttribute('categories');        /**         * The line of code above just gets us an array of category IDs, so here         * we get the full category details (name, slug, id, etc) that we can         * use to populate the SelectControl.         */        return !!catIds && catIds.length > 0 ?            select('core').getEntityRecords('taxonomy', 'category', {                include: catIds.join(','),                per_page: -1,            }) : [];    });    // We need the post type for setting post meta    const postType = useSelect((select) => {        return select('core/editor').getCurrentPostType();    });    // Get and set the post meta    const [meta, setMeta] = useEntityProp('postType', postType, 'meta');    return (        <SelectControl            label={ __('Primary Category', 'text-domain') }            value={ meta.primary_category }            options={ categories.map(cat => {                return {                    label: cat.name,                    value: cat.id,                }            }) }            onChange={ (value) => setMeta({primary_category: value}) }        />    );};