13

I would like to display a dropdown list of categories (or other taxonomy) inside of a Gutenberg block. I can only think of two ways to do this:

  1. Create an array of the taxonomy in php and use wp_localize_script to make that data available to my block javascript.
  2. Use fetch()? in the block to reach out to the api at /wp-json/wp/v2/categories/ and get all the categories.

Are one of these the preferred method? Is there some other kind of built-in or better way to do this?

Edit

As I continue to research this, I learned of another method available in the Gutenberg plugin and presumably available once this editor becomes part of core: wp.apiFetch(). Apparently, it's a wrapper around fetch which hides away some of the unnecessary parts. Now I'm wondering if this is the preferred method.

  1. Use wp.apiFetch() in the block to reach out to the REST api at /wp/v2/categories and get all the categories.

The Catch

On first glance, it seems to make more sense to use the apiFetch() function. However, because that's asynchronous, the data doesn't get loaded into the JSX element. I'm not sure how to make that data load into the element.

2 Answers 2

25

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.

4
  • 3
    This should be the accepted answer. Works like a charm! Commented Aug 22, 2019 at 0:43
  • 2
    To get only the list of selected terms, use wp.data.select( 'core/editor' ).getEditedPostAttribute( 'my-taxonomy-slug' )
    – Jules
    Commented Apr 24, 2020 at 14:06
  • found a nice tutorial rudrastyh.com/gutenberg/… which handles getEntityRecords() Commented May 26, 2020 at 8:03
  • 1
    And to get a list of currently selected categories: wp.data.select('core/editor').getEditedPostAttribute('categories') which will return an array of selected IDs Commented Nov 12, 2020 at 17:28
2

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
                        }
                    ),
6
  • Thanks Chad. Have you done it this way? If so, have you found that the data gets loaded before the element is rendered? I was running into an issue where the data was not getting loaded in time, and so wasn't "connected" to the element.
    – JakeParis
    Commented Nov 29, 2018 at 2:22
  • 2
    Indeed! If you load it before the edit: part, it gets loaded with the page before the elements are rendered. The constants are the FIRST thing in your block js file. Before you even use registerBlockType you define the constants and give them value. Commented Nov 29, 2018 at 14:41
  • 3
    Also be aware that if you want to use wp.apiFetch in your js file, you need to load the wp-api-fetch file in your PHP file when registering scripts (wp_register_script). See my post here wordpress.stackexchange.com/questions/320483/… Commented Nov 29, 2018 at 14:43
  • Did this actually work for anyone? I've implemented a similar approach to no avail. Promises are resolved asynchronously so I'm not sure how this would prevent the editor from being loaded. Commented Feb 25, 2019 at 20:40
  • @LukeKeller it works for me on production sites. Commented Feb 27, 2019 at 3:17

Your Answer

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

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