1

Is that possible right now?

Running:

wp.data.select('core').getEntityRecords('root', 'taxonomy')

Lists all registered taxonomies, same result with:

wp.data.select('core').getTaxonomies()

Can I pass post type somehow? I want to populate a SelectControl with taxonomies associated with the post, showing all taxonomies will be confusing.

1 Answer 1

2

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>
    );
}
1
  • 1
    Thanks! I was close, but didn't realize you needed to pass an object :)
    – INT
    Jul 27, 2022 at 7:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.