Skip to content

Instantly share code, notes, and snippets.

@pbrocks
Created January 14, 2020 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pbrocks/909a1c460cb142bbe6b6fb84aadc2f19 to your computer and use it in GitHub Desktop.
Save pbrocks/909a1c460cb142bbe6b6fb84aadc2f19 to your computer and use it in GitHub Desktop.
Adding attributes to WordPress block templates
const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
const { InnerBlocks } = wp.blockEditor;
registerBlockType( 'ankit-singh/recipe-card', {
title: __( 'Ankit Recipe Card', 'ankit-singh' ),
icon: {
background: '#008aaa',
foreground: '#ffffff',
src: 'shield'
},
category: 'common',
attributes: {
someTitle: {
type: 'string',
default: 'someTitle from attributes',
},
},
keywords: [
__( 'Recipe Card', 'ankit-singh' ),
__( 'Attributes', 'ankit-singh' ),
__( 'Ingredients List', 'ankit-singh' ),
],
styles: [
{ name: 'under-title', label: 'Under Title', isDefault: true },
{ name: 'over-title', label: 'Over Title' }
],
edit: (props) => {
const { attributes: { someTitle }, setAttributes, className } = props;
const TEMPLATE = [
['core/heading', { placeholder: 'Recipe Title ...', value:someTitle }],
['core/columns', {},
[
['core/column', {},
[
['core/image']
]
],
['core/column', {},
[
['core/paragraph', { placeholder: 'Enter short recipe description...' }],
['core/list', { placeholder: 'Enter ingredients...' }],
['core/button', { text: 'Make this Recipe' }]
]
]
]
]
];
const TEMPLATE2 = [
['core/heading', { placeholder: 'Recipe Title ...', value:someTitle }],
['core/columns', {},
[
['core/column', {},
[
['core/paragraph', { placeholder: 'Enter short recipe description...' }],
['core/list', { placeholder: 'Enter ingredients...' }],
['core/button', { text: 'Make this Recipe' }]
]
],
['core/column', {},
[
['core/image']
]
]
]
]
];
const onChangeTitle = ( newTitle ) => {
setAttributes( { someTitle: newTitle } );
};
return (
<>
<div className={props.className}>
<div>{props.attributes.className}</div>
<InnerBlocks
template={props.attributes.className === 'is-style-under-title' ? TEMPLATE : TEMPLATE2}
templateLock="all"
/>
</div>
</>
);
},
save: (props) => {
return (
<div className={props.className}>
<div>{props.attributes.className}</div>
<InnerBlocks.Content />
</div>
);
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment