Get terms of a taxonomy using useSelect
-
20-05-2021 - |
Question
I'm developing a Gutenberg block and I need to show a dropdown with all the terms of a custom taxonomy in it. I'm using the useSelect
hook for retrieving this data, but it's not working because it gets stuck showing the Loading...
message and there are no errors in the console. I registered the taxonomy with the show_in_rest
arg set to true.
I don't know what I'm doing wrong. Any ideas?
const { registerBlockType } = wp.blocks;
const { Placeholder, SelectControl } = wp.components;
const { useSelect } = wp.data;
const blockAttributes = {
slug: {
type: 'string',
default: '',
},
};
export const name = 'my-plugin/my-terms-block';
export const settings = {
title: 'My Terms Block' ),
attributes: blockAttributes,
edit: ( props => {
const { attributes, className } = props;
const terms = useSelect( ( select ) =>
select( 'core' ).getEntityRecords( 'taxonomy', 'my_taxonomy', { per_page: -1, orderby: 'name', order: 'asc', _fields: 'name,slug' } )
);
const setSlug = value => {
props.setAttributes( { slug: value } );
};
if ( ! terms ) {
return 'Loading...';
}
if ( terms.length === 0 ) {
return 'No terms found' );
}
var options = [];
options.push( {
label: 'Select a term...',
value: ''
} );
for ( var i = 0; i < terms.length; i++ ) {
options.push( {
label: terms[i].name,
value: terms[i].slug
} );
}
return (
<Placeholder
key='my-terms-block'
label={ 'Terms Block' }
className={ className }>
<SelectControl
label={ 'Select a term:' }
value={ attributes.slug }
options={ options }
onChange={ setSlug }
/>
</Placeholder>
);
} ),
};
registerBlockType( name, settings );
Solution
If you use the _fields
argument, then it needs to include id
. Otherwise, getEntityRecords()
will always return a null
, even if the REST API request succeeded.
So to fix the issue in question, you just need to add id
to your args, i.e. _fields: 'id,name,slug'
.
You should also know that per_page
is limited to 100
, so even if you set it to a greater number or even -1
(which means all), the value is always set to max 100.