Gutenberg taxonomies - markhowellsmead/helpers GitHub Wiki
Monitoring changes to taxonomy fields
For example, outputting the current post category name in a block.
Because the category name can change independently from the block, we have to
render it dynamically in PHP using a ServerSideRender
component.
In order to reload the preview of the block in the editor, we need to trigger
a refresh of the block when the user clicks a category on/off, but hasn't
yet saved the post. Do this by using a Higher Order Component (HOC) wrapped
around the Edit
class, which automatically reacts when a category provided by
wp.data.select( 'core/editor' ).getEditedPostAttribute( 'categories' )
changes.
(This occurs immediately when the user clicks a category checkbox.)
- Use a block attribute
categories
of typeArray
to a) trigger the refresh and b) pass the selected, as yet unsaved categories to the server-side-render function. - Use
setAttribute
whenever therender
function in theEdit
Component is called to force a refresh of theServerSideRender
component. - Render the HTML of the block on the server based on the current view scope. If the view is being rendered from the editor, use the Array attribute. Otherwise, use the following code in PHP.
$categories = get_terms([
'taxonomy' => 'category',
'number' => -1,
'include' => $attributes['categories'],
'hide_empty' => false,
'orderby' => 'include',
]);