I want to extend the WordPress (Gutenberg) default block Paragraph to give editors the possibility to add tooltips without writing code.
Goal:
- Add block paragraph and add some text
- Make a text selection and click on a (new) button (should appear next to text styles)
- Tooltip button should work exactly like the link button, only that it should be possible to enter text instead of a link
Working:
- I added a button (Text-Style)
- I can select text and I can add a class (.kf-tooltip)
- I know how to add a Tooltip via JS
Missing:
- How to add the Popover to enter the text for the tooltip
- How to store / save this data
- How to output this data as attribute (for example: data-tooltip="Lorem ipsum")
Any help would be awesome!
WordPress Plugin
<?php
/*
Plugin Name: KF Custom
*/
add_action( 'enqueue_block_editor_assets', function () {
wp_enqueue_script(
'kf-custom-script',
plugins_url( 'kf-custom-script.js', __FILE__ ),
array('wp-blocks', 'wp-rich-text')
);
});
add_action( 'enqueue_block_assets', function () {
wp_enqueue_style( 'kf-custom-style', plugins_url( 'style.css', __FILE__ ) );
});
kf-custom-script.js
(function(wp){
console.log(wp);
// Create Popover
const { Popover } = wp.components;
var MyCustomButton = function( props ) {
return wp.element.createElement(
wp.blockEditor.RichTextToolbarButton, {
icon: 'editor-code',
title: 'Tooltip',
onClick: function() {
console.log('Open Popup on this event');
props.onChange( wp.richText.toggleFormat(
props.value,
{ type: 'my-custom-format/kf-tooltip' }
) );
},
isActive: props.isActive,
}
);
}
var clickHandler = function( props ) {
console.log('Open Popup on this event');
return 'test';
}
wp.richText.registerFormatType(
'my-custom-format/kf-tooltip', {
title: 'Tooltip',
tagName: 'span',
className: 'kf-tooltip',
edit: MyCustomButton,
click: clickHandler
}
);
})(window.wp)