I’m the author of a plugin called Radio Buttons for taxonomies which converts certain taxonomy metaboxes (in classic) and sidebars (block editor) to use Radio buttons instead of checkboxes for selecting a term.
Unlike with checkboxes, which you can simply uncheck, with radio buttons if you want to offer someone the chance to “undo” a selection (or not apply a term) you need to provide an additional “term” they can select and then no save any value. It’s a sort of pseudo term if you will.
Due to this, I filter the result of get_terms() and add a fake term with a 0 value. On save, I check for a 0 value for the term and make sure there are no terms saved for that post.
To reduce it to something y’all can test, here’s an example code snippet:
/**
* Add new 0 or null term in metabox and quickedit
* this will allow users to "undo" a term if the taxonomy is not required
*
* @param array $terms Array of found terms.
* @param array $taxonomies An array of taxonomies.
* @param array $args An array of get_terms() arguments.
* @return array
*/
function kia_get_terms( $terms, $taxonomies, $args ) {
if ( isset( $args['fields'] ) && $args['fields'] == 'all' ) {
$no_term = esc_html__( 'No term', 'my-text-domain' );
$uncategorized = (object) array(
'term_id' => 0,
'count' => 0,
'description' => '',
'name' => $no_term,
'slug' => '0',
'taxonomy' => 'category',
'parent' => '0',
);
array_push( $terms, new WP_Term( $uncategorized ) );
}
return $terms;
}
add_filter( 'get_terms', 'kia_get_terms', 10, 3 );
In the classic editor, this works fine. But in the block editor (which still fetches the terms using get_terms() via the REST API… this causes an Uncaught (in promise) error and seems to get stuck in an infinite loop. How can I prevent this from looping?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The problem is you are passing “term_id” as 0 in your code. Use -1 instead!. It will definitely show up in the Block Editor. I guess this is a bug of Gutenberg though.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0
