Skip to content

Instantly share code, notes, and snippets.

@fumikito
Last active November 28, 2020 15:56
Show Gist options
  • Save fumikito/574c8276aac539967e05270501ed7c07 to your computer and use it in GitHub Desktop.
Save fumikito/574c8276aac539967e05270501ed7c07 to your computer and use it in GitHub Desktop.
Force something in block editor and change post title programatically
/*!
* Force post title to include "WordPress"
*
* @deps wp-data, wp-dom-ready, wp-element, wp-components
*/
const { data, domReady } = wp;
const { render, Component } = wp.element;
const { Modal, Button, TextControl } = wp.components;
class ModalContainer extends Component {
constructor( props ) {
super( props );
const title = data.select( 'core/editor' ).getEditedPostAttribute( 'title' );
this.state = {
valid: this.isValid( title ),
title: title,
};
}
componentDidMount() {
const { valid } = this.state;
data.subscribe( () => {
// If title doesn't contain "WordPress", force edit.
const title = data.select( 'core/editor' ).getEditedPostAttribute( 'title' );
const newValue = this.isValid( title );
if ( valid !== newValue ) {
this.setState( {
valid: newValue,
title: title,
} );
}
} );
}
render() {
const { valid, title } = this.state;
if ( ! valid ) {
return <Modal
shouldCloseOnClickOutside={ false }
isDismissible={ false }
shouldCloseOnEsc={ false }
title='Title must include "WordPress"'
onRequestClose={ () => {
if ( this.isValid( title ) ) {
this.setState( {
valid: true,
} );
}
} }>
<TextControl value={ title } onChange={ ( value ) => {
this.setState( {
title: value,
} );
} } label={ 'New Title' } />
{ this.isValid( title ) ? null : (
<p className="description">Invalid</p>
) }
<Button isSecondary disabled={ ! this.isValid( title ) } onClick={ () => {
if ( this.isValid( title ) ) {
this.setState( {
valid: true,
title: title,
}, () => {
data.dispatch( 'core/editor' ).editPost( {
title: title,
} );
} );
}
} }>
Set Title
</Button>
</Modal>;
} else {
return null;
}
}
isValid( title) {
return /WordPress/i.test( title );
}
}
// Add DOM in editor screen and register as React app.
domReady( () => {
const wrapper = document.createElement( 'div' );
document.getElementsByTagName( 'body' )[0].appendChild( wrapper );
render( <ModalContainer />, wrapper );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment