Skip to content

Instantly share code, notes, and snippets.

@gilbertoalbino
Created September 13, 2020 20:30
Show Gist options
  • Save gilbertoalbino/027096bd577497b70710b308a8f228b0 to your computer and use it in GitHub Desktop.
Save gilbertoalbino/027096bd577497b70710b308a8f228b0 to your computer and use it in GitHub Desktop.
block.js
var wpddb = {}
wpddb.contentTag = 'p';
wpddb.contentClass = 'wpddb-content';
(function (blocks, editor, element) {
var el = wp.element.createElement;
var RichText = editor.RichText;
blocks.registerBlockType('wpddb/promotion', {
title: 'WPDDB Promotion',
icon: 'universal-access-alt',
category: 'layout',
attributes: {
content: {
type: 'array',
source: 'children',
selector: '.' + wpddb.contentClass, // using specific selector
},
},
edit: function (props) {
var content = props.attributes.content;
function onChangeContent(newContent) {
props.setAttributes({content: newContent});
}
return (
el(
el('h1', {}, 'Back end'),
RichText,
{
tagName: wpddb.contentTag,
value: content,
onChange: onChangeContent,
className: wpddb.contentClass,
}
)
);
},
save: function () {
return (
el('h1', {}, 'Front end.'),
el(RichText.Content, {
tagName: wpddb.contentTag,
value: props.attributes.content,
className: wpddb.contentClass,
})
);
},
});
}(
window.wp.blocks,
window.wp.editor,
window.wp.element,
));
@lotharthesavior
Copy link

Hi, @gilbertoalbino,

Thanks for reaching out.

Since the code was written, some things changed: we need to wrap the return with elements instead of simple parenthesis, and the wpddb.contentTag must be present in the wrapper element. Here is the snippet with the fixes: https://gist.github.com/lotharthesavior/2d536e2f25ee86f57c259e87bf7d4354

There, I also updated the component at the bottom because they are deprecating the wp.editor.RichText in favor of wp.blockEditor.RichText.

Also, there was an error in the code: the save method needs the props parameter to be present in order to work.

We are working to fix it in the book.

Cheers,
Savio Resende

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment