WordPress.org

WordPress Developer Blog

Snippet: How to add custom blocks to navigation menus

Snippet: How to add custom blocks to navigation menus

In WordPress, the Navigation block restricts the types of blocks that can be added by default. However, there may be cases where you need to include custom blocks or additional Core blocks within navigation menus. For example, you might have to build a custom block for specific functionality, such as a mega menu or a block that displays a shopping cart on an eCommerce site. The use cases are numerous.
In this post you will learn how to add unsupported blocks to the Navigation block. This process requires JavaScript. The first step is to enqueue a JavaScript file using the `enqueue_block_editor_assets` hook. This ensures that your script is correctly loaded in the Editor.

add_action( 'enqueue_block_editor_assets', function() {
    wp_enqueue_script(
        'example-add-block-to-navigation-editor-script',
        plugins_url( 'js/editor-script.js', __FILE__ ),
        array( 'wp-hooks', 'wp-blocks' ), // Dependencies for block filters.
        '1.0.0',
        true
    );
} );

If you are following this example step-by-step, start by creating a file named `editor-script.js`. Place this file inside a `js` folder in your plugin’s root directory. Then, add the following code:

const addToNavigation = ( blockSettings, blockName ) => {
	if ( blockName === 'core/navigation' ) {
		return {
			...blockSettings,
			allowedBlocks: [
				...( blockSettings.allowedBlocks ?? [] ),
				'core/image',
				// example/custom-block
			],
		};
	}
	return blockSettings;
};

wp.hooks.addFilter(
	'blocks.registerBlockType',
	'example-add-block-to-navigation',
	addToNavigation
);

This code uses the `blocks.registerBlockType` filter to extend the `allowedBlocks` property of the `core/navigation` block. For the purposes of this snippet, the code adds the `core/image` block to the Navigation block. Replace this with the name of the block you wish to add. 

Relevant links

Props to @bph and @areziaal for editorial and technical reviews.

3 responses to “Snippet: How to add custom blocks to navigation menus”

  1. Andry Avatar
    Andry

    Really bad implementation of the Navigation Block — you can’t easily set your own burger icon, change breakpoints, or tweak mobile/desktop layouts. This thing is just frustrating to work with.

    1. Rodrigo Avatar
      Rodrigo

      Hear hear.

    2. Dave Avatar
      Dave

      Amen. This is ridiculous to put a simple icon in the navigation bar.

Leave a Reply

Your email address will not be published. Required fields are marked *