Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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