admin管理员组

文章数量:1193808

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.

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.

Share Improve this question asked Jul 26, 2022 at 20:17 INTINT 1,2813 gold badges21 silver badges51 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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>
    );
}

本文标签: custom taxonomyGetting taxonomies associated with a specified post type