Skip to content

Instantly share code, notes, and snippets.

@geoffreycrofte
Created December 10, 2022 17:42
Show Gist options
  • Save geoffreycrofte/c566fa62b028c117e5c18c4c5135bc15 to your computer and use it in GitHub Desktop.
Save geoffreycrofte/c566fa62b028c117e5c18c4c5135bc15 to your computer and use it in GitHub Desktop.
Create a Gutenberg block using a shortcode for the front, and getting its parameter from the front panel
/**
* Code writen on the fly, I still need to test it.
* Use at your own risk 😁
*/
// Register the block with WordPress
registerBlockType('my-plugin/my-block', {
title: 'My Block',
icon: 'book',
category: 'common',
// Set up the block attributes
attributes: {
text: {
type: 'string',
default: 'Default text',
}
},
// Define the block editor interface
edit: function(props) {
// Retrieve the text attribute
const text = props.attributes.text;
// Define the save function
function updateText(event) {
props.setAttributes({ text: event.target.value });
}
// Render the control panel
return (
<div>
<label>
Block text:
<input type="text" value={text} onChange={updateText} />
</label>
</div>
);
},
// Define the front-end output
save: function(props) {
// Retrieve the text attribute
const text = props.attributes.text;
// Use a shortcode to generate the output
return (
<p>
[my_shortcode text="{text}"]
</p>
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment