Wordpress - How would I get a taxonomy/category list inside a Gutenberg block?
You don't need apiFetch
or localization to get a list of all categories. You can do this with the wp.data
module:
wp.data.select('core').getEntityRecords('taxonomy', 'category');
See the Gutenberg Handbook entry on Core Data for more details.
Load the elements into a constant using a function like this:
const postSelections = [];
const allPosts = wp.apiFetch({path: "/wp/v2/posts"}).then(posts => {
postSelections.push({label: "Select a Post", value: 0});
$.each( posts, function( key, val ) {
postSelections.push({label: val.title.rendered, value: val.id});
});
return postSelections;
});
Then use postSelections as your element "options".
el(
wp.components.SelectControl,
{
label: __('Select a Post'),
help: 'Select a post to display as a banner.',
options: postSelections,
value: selectedPost,
onChange: onChangePost
}
),