Skip to content

Instantly share code, notes, and snippets.

@imath
Created March 1, 2020 03:52
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imath/3ff883c109e16c762c32562098619b8d to your computer and use it in GitHub Desktop.
Save imath/3ff883c109e16c762c32562098619b8d to your computer and use it in GitHub Desktop.
Example of use of the filter to replace the PostTaxonomy panel of the WordPress Block Editor
const { createElement, Component } = wp.element;
const { compose } = wp.compose;
const { RadioControl } = wp.components;
const { withSelect, withDispatch } = wp.data;
const { addFilter } = wp.hooks;
const { apiFetch } = wp;
const { __ } = wp.i18n;
class RiskDomain extends Component {
constructor() {
super( ...arguments );
this.state = {
checked: 0,
options: [],
message: '',
};
}
componentDidMount() {
const { risk } = this.props;
if ( risk && risk[0] ) {
this.setState( {
checked: risk[0],
} );
}
apiFetch( { path: '/wp/v2/domain?extendedContext=risk-ops' } ).then( terms => {
const options = terms.map( ( term ) => {
return { label: term.name, value: term.id };
} );
this.setState( { options: options, message: '' } );
}, error => {
this.setState( { message: error.message } );
} );
}
onUpdateRisk( checked ) {
const { onChangeRisk } = this.props;
this.setState( {
checked: parseInt( checked.option, 10 ),
} );
onChangeRisk( checked.option );
}
render() {
const { checked, options, message } = this.state;
const { taxonomy } = this.props;
let radioGroup;
if ( options && options.length > 1 ) {
radioGroup = (
<RadioControl
selected={ checked }
options={ options }
onChange={ ( option ) => { this.onUpdateRisk( { option } ) } }
/>
);
}
return (
<div>
{ taxonomy && '' !== taxonomy.description && (
<p>{ taxonomy.description }</p>
) }
{ radioGroup }
{ message && (
<p className="error">{ message }</p>
) }
</div>
);
}
}
const RiskDomainWrapper = compose( [
withSelect( ( select ) => {
return {
risk: select( 'core/editor' ).getEditedPostAttribute( 'domain' ),
};
} ),
withDispatch( ( dispatch ) => ( {
onChangeRisk( riskId ) {
dispatch( 'core/editor' ).editPost( { domain: [ riskId ] } );
},
} ) ),
] )( RiskDomain );
const riskDomainFilter = ( OriginalComponent ) => {
return ( props ) => {
const { slug } = props;
if ( 'domain' === slug ) {
return <RiskDomainWrapper {...props} />
}
return <OriginalComponent {...props} />
};
}
addFilter(
'editor.PostTaxonomyType',
'riskop-domain',
riskDomainFilter
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment