Yes, you can pass a post type to getEntityRecords()
and also getTaxonomies()
, both using the same format which is an object of arguments:
-
Using
getEntityRecords()
:wp.data.select( 'core' ).getEntityRecords( 'root', 'taxonomy', { type: 'post' } )
-
Using
getTaxonomies()
: ( which is actually a shorthand for the above code )wp.data.select( 'core' ).getTaxonomies( { type: 'post' } )
See the REST API handbook for the list of accepted arguments: https://developer.wordpress.org/rest-api/reference/taxonomies/
Working example using getTaxonomies()
So this is for a block type with a string attribute named taxonomy
(which stores the taxonomy slug), and I’m using useSelect
:
function edit( { attributes, setAttributes } ) {
// just an example which defines a dynamic post type
const postType = useSelect( select => {
const { getCurrentPostType } = select( 'core/editor' );
return getCurrentPostType();
}, [] );
// fetch the post type's taxonomies from the REST API, or retrieve them from the cache
const taxonomies = useSelect( select => {
const { getTaxonomies } = select( 'core' );
return getTaxonomies( { type: postType } );
}, [ postType ] );
// build the options object for SelectControl - remember that `taxonomies` could be a
// null if the REST API request hasn't yet been fully resolved
const options = taxonomies?.map( taxonomy => ( {
label: `${ taxonomy.name } (${ taxonomy.slug })`,
value: taxonomy.slug,
} ) );
return (
<div { ...useBlockProps() }>
<SelectControl
label="Taxonomy"
value={ attributes.taxonomy }
options={ options }
onChange={ value => setAttributes( { taxonomy: value } ) }
__nextHasNoMarginBottom
/>
</div>
);
}