• Hello all,
    I am completely unfamiliar with registering custom elements for gutenberg and I would be so happy to receive some feedback on the following code.

    (function () {
    const { __ } = wp.i18n;
    const { registerFormatType, toggleFormat } = wp.richText;
    const { RichTextToolbarButton } = wp.blockEditor || wp.editor;
    const { createElement, Fragment } = wp.element;

    registerFormatType('custom/tooltip', {
    title: __('Tooltip', 'custom-tooltip'),
    tagName: 'span',
    className: 'custom-tooltip',
    attributes: {
    'data-tooltip': 'data-tooltip', // Custom attribute for the tooltip text
    },
    edit({ isActive, value, onChange }) {
    return createElement(
    Fragment,
    {},
    createElement(
    RichTextToolbarButton,
    {
    icon: 'editor-help',
    title: __('Add Tooltip', 'custom-tooltip'),
    onClick: () => {
    const tooltipText = prompt(__('Enter tooltip text:', 'custom-tooltip'));
    if (tooltipText) {
    onChange(
    toggleFormat(value, {
    type: 'custom/tooltip',
    attributes: { 'data-tooltip': tooltipText },
    })
    );
    }
    },
    isActive: isActive,
    }
    )
    );
    },
    });
    })();

    and the php

    function wp_tooltip_inline_enqueue_assets() {
    // Enqueue JavaScript for the editor
    wp_enqueue_script(
    'wp-tooltip-inline',
    plugin_dir_url(__FILE__) . 'tooltip-inline.js',
    array('wp-rich-text', 'wp-editor', 'wp-element', 'wp-components', 'wp-i18n'),
    filemtime(plugin_dir_path(__FILE__) . 'tooltip-inline.js'),
    true
    );

    // Enqueue CSS for the editor styling
    wp_enqueue_style(
    'wp-tooltip-inline-css',
    plugin_dir_url(__FILE__) . 'tooltip-inline.css',
    array(),
    filemtime(plugin_dir_path(__FILE__) . 'tooltip-inline.css')
    );
    }
    add_action('enqueue_block_editor_assets', 'wp_tooltip_inline_enqueue_assets');

    // Enqueue CSS for the frontend
    function wp_tooltip_inline_enqueue_frontend_styles() {
    wp_enqueue_style(
    'wp-tooltip-inline-css',
    plugin_dir_url(__FILE__) . 'tooltip-inline.css',
    array(),
    filemtime(plugin_dir_path(__FILE__) . 'tooltip-inline.css')
    );
    }
    add_action('wp_enqueue_scripts', 'wp_tooltip_inline_enqueue_frontend_styles');
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)

The topic ‘registerFormatType’ is closed to new replies.