Skip to content

Instantly share code, notes, and snippets.

@nicomollet
Last active November 14, 2023 13:29
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 nicomollet/02c1a0e3920f3c889d8693a1dbd1af53 to your computer and use it in GitHub Desktop.
Save nicomollet/02c1a0e3920f3c889d8693a1dbd1af53 to your computer and use it in GitHub Desktop.
WordPress block editor: add data-modal attribute to button block.
/**
* Button block, add a "data-modal" attribute.
*
* @author Nicolas Mollet, inspired by Marie Comet
* @see https://mariecomet.fr/en/2021/12/14/adding-options-controls-existing-gutenberg-block/
*/
const { __ } = wp.i18n;
// Enable custom attributes on Button block
const enableSidebarSelectOnBlocks = [
'core/button'
];
const { createHigherOrderComponent } = wp.compose;
const { Fragment } = wp.element;
const { InspectorControls } = wp.blockEditor;
const { PanelBody, TextControl } = wp.components;
/**
* Declare our custom attribute.
*
* @param {Object} settings Settings
* @param {String} name Name
* @return {*}
*/
const setSidebarSelectAttribute = ( settings, name ) => {
if ( ! enableSidebarSelectOnBlocks.includes( name ) ) {
return settings;
}
return Object.assign( {}, settings, {
attributes: Object.assign( {}, settings.attributes, {
dataModalAttribute: { type: 'string' }
} ),
} );
};
wp.hooks.addFilter(
'blocks.registerBlockType',
'custom-attributes/set-sidebar-select-attribute',
setSidebarSelectAttribute
);
/**
* Add Custom Select to Button Sidebar
*/
const withSidebarSelect = createHigherOrderComponent( ( BlockEdit ) => {
return ( props ) => {
// If current block is not allowed
if ( ! enableSidebarSelectOnBlocks.includes( props.name ) ) {
return (
<BlockEdit { ...props } />
);
}
const { attributes, setAttributes } = props;
const { dataModalAttribute } = attributes;
return (
<Fragment>
<BlockEdit { ...props } />
<InspectorControls>
<PanelBody
title={ __( 'Open in a Modal?' ) }
>
<TextControl
label={ __( 'Modal name (starting with #)' ) }
value={ dataModalAttribute }
onChange={ ( value ) => {
setAttributes( {
dataModalAttribute: value,
} );
} }
/>
</PanelBody>
</InspectorControls>
</Fragment>
);
};
}, 'withSidebarSelect' );
wp.hooks.addFilter(
'editor.BlockEdit',
'custom-attributes/with-sidebar-select',
withSidebarSelect
);
<?php
function render_block_button_datamodal( string $block_content, array $block ){
if ( 'core/button' === $block['blockName'] && ! empty( $block['attrs']['dataModalAttribute'] ) ) {
$block_content = str_replace('<a ', '<a data-modal="'. esc_attr($block['attrs']['dataModalAttribute']) . '"', $block_content);
}
return $block_content;
}
add_filter( 'render_block', 'render_block_button_datamodal', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment