Skip to content

Instantly share code, notes, and snippets.

@misfist
Created November 5, 2020 20:47
Show Gist options
  • Save misfist/502b98bf05464c629614d0cf975cd5cc to your computer and use it in GitHub Desktop.
Save misfist/502b98bf05464c629614d0cf975cd5cc to your computer and use it in GitHub Desktop.
Gutenberg - Custom Taxonomy Selector - Radio
/**
* External dependencies
*/
import { unescape as unescapeString } from 'lodash';
function customTaxonomyRadioSelector( OriginalComponent ) {
return function( props ) {
if ( props.slug === 'my_taxonomy') {
if ( ! window.HierarchicalTermRadioSelector ) {
window.HierarchicalTermRadioSelector = class HierarchicalTermRadioSelector extends OriginalComponent {
// Return only the selected term ID
onChange( event ) {
const { onUpdateTerms, taxonomy } = this.props;
const termId = parseInt( event.target.value, 10 );
onUpdateTerms( [ termId ], taxonomy.rest_base );
}
// Copied from HierarchicalTermSelector, changed input type to radio
renderTerms( renderedTerms ) {
const { terms = [] } = this.props;
return renderedTerms.map( ( term ) => {
const id = `editor-post-taxonomies-hierarchical-term-${ term.id }`;
return (
<div key={ term.id } className="editor-post-taxonomies__hierarchical-terms-choice">
<input
id={ id }
className="editor-post-taxonomies__hierarchical-terms-input"
type="radio"
checked={ terms.indexOf( term.id ) !== -1 }
value={ term.id }
onChange={ this.onChange }
/>
<label htmlFor={ id }>{ unescapeString( term.name ) }</label>
{ !! term.children.length && <div className="editor-post-taxonomies__hierarchical-terms-subchoices">{ this.renderTerms( term.children ) }</div> }
</div>
);
} );
}
};
}
return <window.HierarchicalTermRadioSelector { ...props } />;
}
return <OriginalComponent { ...props } />;
};
}
wp.hooks.addFilter( 'editor.PostTaxonomyType', 'core-functionality', customTaxonomyRadioSelector );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment