Skip to content

Instantly share code, notes, and snippets.

@ashwebstudio
Last active February 24, 2024 19:46
Show Gist options
  • Save ashwebstudio/17846c1ae70530717e8f2a220925918c to your computer and use it in GitHub Desktop.
Save ashwebstudio/17846c1ae70530717e8f2a220925918c to your computer and use it in GitHub Desktop.
Single toggle + text attribute for core button block
/*
Adding a toggle and conditional text input to core button block
As used in Conversion Bridge, https://conversionbridgewp.com
*/
(function(wp) {
// Load dependencies.
var el = wp.element.createElement;
var Fragment = wp.element.Fragment;
var TextControl = wp.components.TextControl;
var ToggleControl = wp.components.ToggleControl;
var PanelBody = wp.components.PanelBody;
var createHigherOrderComponent = wp.compose.createHigherOrderComponent;
var addFilter = wp.hooks.addFilter;
// Add attributes for text box and label.
function addAttributes(settings) {
if (settings.name === 'core/button') {
settings.attributes = Object.assign(settings.attributes, {
conversionTracking: {
type: 'boolean',
default: false,
},
conversionLabel: {
type: 'string',
default: '',
}
});
}
return settings;
}
// Add the attributes.
addFilter(
'blocks.registerBlockType',
'conversion-bridge/conversion-tracking-attributes',
addAttributes
);
// Create HOC to add the toggle control and text control.
var withConversionControls = createHigherOrderComponent(function(BlockEdit) {
return function(props) {
if (props.name !== 'core/button') { // Only for core button.
return el(BlockEdit, props);
}
var attributes = props.attributes;
var setAttributes = props.setAttributes;
return el(
Fragment, // ??
null, // ??
el(BlockEdit, props), // ??
el( // ??
wp.editor.InspectorControls, // ??
null, // ??
el(
PanelBody, // Create a custom panel
{
title: 'Conversion Tracking',
initialOpen: true
},
el( // Add toggle control element.
ToggleControl,
{
label: 'Enable Conversion Tracking',
checked: attributes.conversionTracking,
onChange: function(newValue) {
setAttributes({ conversionTracking: newValue });
}
}
),
attributes.conversionTracking && el( // Only show this optional text input if conversion tracking is enabled.
TextControl,
{
label: 'Conversion Tracking Label',
value: attributes.conversionLabel,
onChange: function(newValue) {
setAttributes({ conversionLabel: newValue });
}
}
)
)
)
);
};
}, 'withConversionControls');
// Add the filter on the existing settings for a button block.
addFilter(
'editor.BlockEdit',
'conversion-bridge/conversion-tracking-attributes',
withConversionControls
);
})(window.wp);
add_action( 'enqueue_block_editor_assets', 'enqueue_custom_block_script' );
function enqueue_custom_block_script() {
wp_enqueue_script(
'conversion-bridge-block-button',
CONVERSION_BRIDGE_PLUGIN_URL . '/assets/js/block-button.js',
array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor', 'wp-components' )
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment