I built a custom single-selection CategorySelector
component for the WordPress Gutenberg editor a while back, but realised on a current project that I had omitted to include hierarchical category support. I needed to swap out the SelectControl
with a TreeSelect
.
(tl;dr: the code for the new component is here.)
After a bit of battling, I managed to strip out the more complex withSelect
syntax and add useSelect
instead (using the reasoning and methods I wrote about just recently), then implementing a function within the amended component to convert the regular REST API response into a hierarchical array.
The function takes the flat array (which is pulled in from the REST API using select('core').getEntityRecords('taxonomy', 'category')
) and uses the lodash groupBy to group the categories according to their parent IDs. The fillWithChildren
function then modifies the resultant array so that the children property is available (which makes the TreeSelect
work).
import { groupBy } from 'lodash';
export const buildTermsTree = (flatTerms) => {
const termsByParent = groupBy(flatTerms, 'parent');
const fillWithChildren = (terms) => {
return terms.map((term) => {
const children = termsByParent[term.id];
return {
...term,
children: children && children.length ? fillWithChildren(children) : [],
};
});
};
return fillWithChildren(termsByParent['0'] || []);
};
Leave a Reply