Skip to content

Instantly share code, notes, and snippets.

@hrsetyono
Created Mar 14, 2022
Embed
What would you like to do?
(function() {
const el = wp.element.createElement;
const { Fragment } = wp.element;
const { InspectorControls, MediaUpload } = wp.blockEditor;
const { createHigherOrderComponent } = wp.compose;
const { addFilter } = wp.hooks;
const { Button, PanelBody } = wp.components;
addFilter('blocks.registerBlockType', 'extend-cover/attributes', addAttribute);
addFilter('editor.BlockEdit', 'extend-cover/edit', createHigherOrderComponent(addControl));
addFilter('blocks.getSaveElement', 'extend-cover/save', customSave);
function addAttribute(settings, name) {
// Abort if not Cover
if (!['core/cover'].includes(name)) {
return settings;
}
// add new attribute
settings.attributes = Object.assign(settings.attributes, {
mobileImageID: { type: 'number' },
mobileImageURL: { type: 'string' },
});
return settings;
}
function addControl(BlockEdit) {
return (props) => {
if (!['core/cover'].includes(props.name)) {
return el(BlockEdit, props);
}
const atts = props.attributes;
return el(Fragment, {},
el(BlockEdit, props),
el(InspectorControls, {},
el(PanelBody, {
title: 'Mobile Cover',
initialOpen: true,
},
el('div', {},
( atts.mobileImageURL &&
el('img', {
src: atts.mobileImageURL
})
),
el(MediaUpload, {
allowedTypes: 'image',
value: atts.mobileImageID,
onSelect: setMobileImage,
render: renderMobileImage,
})
)
)
)
);
function setMobileImage(media) {
props.setAttributes({
mobileImageURL: media.url,
mobileImageID: media.id,
});
}
function renderMobileImage(obj) {
if(atts.mobileImageURL) {
atts.className = atts.className.replace( /has-mobile-image/, '' );
atts.className += ' has-mobile-image';
}
const buttonLabel = atts.mediaID ? 'Change image' : 'Upload image';
return el(Button, {
className: atts.mobileImageID ? 'button button--transparent' : 'button',
onClick: obj.open,
},
buttonLabel
);
}
}
}
function customSave(element, blockType, atts) {
// Abort if not cover block
if(blockType.name !== 'core/cover') { return element; }
// Put the mobile image as CSS var
if(atts.mobileImageURL) {
element.props.style['--mobileImage'] = `url("${atts.mobileImageURL}")`;
}
return element;
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment