1

I am building a custom plugin.

My first goal is to insert a button to the Block Editor Header Toolbar (shown as a red rectangle).

The button is independent from selected blocks, so it would always be visible.

I have a basic php file, which enques the scripts and styles, and I only have an index.js file.

Any help would be much appreciated!

toolbar

1 Answer 1

1

There is no official public API to inject custom buttons into that area. This can be confirmed by inspecting the source code for this area, rendered by the DocumentTools component in the @wordpress/editor package.

As alternatives, you could render a button to the right of the Save/Publish button on the right side. This button would then toggle a sidebar where you could house your plugin's controls. You'd do this by using the <PluginSidebar> component:

import { __ } from '@wordpress/i18n';
import { PluginSidebar } from '@wordpress/editor';
import { PanelBody } from '@wordpress/components';
import { registerPlugin } from '@wordpress/plugins';

const PluginSidebarExample = () => {
    return (
        <PluginSidebar
            name="plugin-sidebar-example"
            title={ __( 'My PluginSidebar' ) }
            icon={ 'smiley' }
        >
            <PanelBody>
                …
            </PanelBody>
        </PluginSidebar>
    )
};

// Register the plugin.
registerPlugin( 'plugin-sidebar-example', { render: PluginSidebarExample } );

Or for just a single button that does something on activation, you could add a menu item under the More menu using the <PluginMoreMenuItem> component:

import { registerPlugin } from '@wordpress/plugins';
import { PluginMoreMenuItem } from '@wordpress/editor';
import { image } from '@wordpress/icons';

const MyButtonMoreMenuItemTest = () => (
    <PluginMoreMenuItem
        icon={ image }
        onClick={ () => {
            alert( 'Button Clicked' );
        } }
    >
        More Menu Item
    </PluginMoreMenuItem>
);

registerPlugin( 'more-menu-item-test', { render: MyButtonMoreMenuItemTest } );

Otherwise, if you do really want the button in the area you indicate, you'd need to look at having some custom JavaScript that injects HTML into that portion of the editor. You could query for an existing element in the DOM by class name, and then inject a custom DOM button into the area.

1
  • Thank you very much! I think I can make use of the PluginSidebar! Commented Oct 30 at 18:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.