Search code examples
wordpresswordpress-gutenberggutenberg-blocks

Wordpress - Custom Heading Block


So I've seen wordpress's heading block where you can choose what heading tag the title is, so h1, h3 etc.... I'm making my own custom gutenberg blocks and i'd like to implement this heading tag switch feature where you can dynamically change the h tag of the title within my custom block.

The only problem is it seems to be somewhat difficult to find out how this wordpress block functions. I can't seem to find any developer docs or github code or anything.

So my question is are there developer docs? or how does this heading block work? im not sure where to start.

Thanks.


Solution

  • The docs for Gutenberg are pretty rough, but if you are willing to dig through the code you can usually find what you are looking for. Here is the code that creates the heading level dropdown for the Heading block in Gutenberg.

    And below is a simplified version of what the Heading block does.

    Use a <Toolbar> component to select the heading tag:

    <Toolbar label={ __('Change heading tag', 'text-domain') }>
        <ToolbarGroup
            isCollapsed={ true }
            controls={ [
                {
                    tag: 'h1',
                    label: __('Heading 1', 'text-domain'),
                },
                {
                    tag: 'h2',
                    label: __('Heading 2', 'text-domain'),
                },
                {
                    tag: 'h3',
                    label: __('Heading 3', 'text-domain'),
                },
                {
                    tag: 'h4',
                    label: __('Heading 4', 'text-domain'),
                },
                {
                    tag: 'h5',
                    label: __('Heading 5', 'text-domain'),
                },
                {
                    tag: 'h6',
                    label: __('Heading 6', 'text-domain'),
                }
            ].map((tag) => {
                return {
                    title: tag.label,
                    isActive: headingTag === tag.tag,
                    onClick: () => setAttributes({'headingTag': tag.tag}),
                }
            }) }
        />
    </Toolbar>
    

    Then in your edit/save function you can set the component tag with a <RichText> component:

    <RichText
        tagName={ headingTag }
        value={ content }
        onChange={ value => setAttributes({content: value}) }
    />
    

    Technically the Heading block uses an integer attribute called level for storing the 1, 2, 3, etc. Then they create the heading level by prepending h to level attribute. The above example lets you use additional HTML tags if you want by storing the entire HTML tag name (e.g. <p>, <div>, etc.).