Created
March 1, 2020 03:52
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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