Development

 / 

Headstartwp

 / 

WordPress

HeadstartWP – Create a custom Gutenberg block

As always we go against the grain and start with the documentation https://developer.wordpress.org/block-editor/, you can say anything about WordPress but its documentation is certainly well done and a gold mine of information.

Having studied the documentation, we can move on to this article. We are going to look at how to create Gutenberg blocks within a theme, and we are going to create a block to use on this blog for presenting highlights on the projects page.

As explained in a previous article, for my WordPress installation I have chosen a parent theme and created my own Child Theme. Let’s take a quick step back, all tutorials I’ve seen so far for creating Gutenberg blocks started by creating a plugin, but in my case I prefer to proceed directly inside the template since these blocks will be used only in this specific theme and will be very simple.

I opened my IDE and from the terminal launched @wordpress/create-block ( https://www.npmjs.com/package/@wordpress/create-block ) to create a starting block that I moved inside the src/blocks/ folder of my Child Theme.

I deleted the auto-generated .php file and moved the block registration inside the functions.php of the template since I do not need to add PHP code for these blocks.

1 2 3 4 5 6 7 8 function prefix_blocks_init() { $blocks = glob(__DIR__ . '/build/blocks/*'); foreach ( $blocks as $block ) { register_block_type( $block ); } } add_action( 'init', 'prefix_blocks_init' );

With this simple function I will register all the blocks that I am going to add inside the blocks folder. I reiterate that you can keep the individual index.php in case there is a need to add PHP code for the blocks.

I also deleted package.json and package-lock.json from the individual block folder to move scripts and dependencies inside the template package.json. Since there are two scripts that respond to the build command I added a subscript to those of the blocks calling them [command]-blocks.

To verify that everything is correct, launch a simple npm run build-blocks and you will see that the compiled code will appear in the build folder and your basic block will be available from the backend of the site.

Let’s customize the default block
The block you generate with @wordpress/create-block is very simple and we need to add some fields: alignment, title, media, description, cta and link.

So let’s go ahead and add this code snippet to our block.json.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 "attributes": { "alignment": { "type": "string", "default": "none" }, "title": { "type": "string", "selector": "h2" }, "mediaID": { "type": "number" }, "mediaURL": { "type": "string" }, "description": { "type": "string", "selector": ".description" }, "ctaLabel": { "type": "string", "selector": ".button" }, "sectionLink": { "type": "object" } },

In order to add the inputs in the edit.js, my advice is to use the ones from the block-library ( https://github.com/WordPress/gutenberg/tree/trunk/packages/block-library/src ) of Gutenberg as a reference since you can be sure that they always use the most up-to-date API. Gutenberg is not a new project, but to this day it is constantly updating and growing so it is always important to take a look at the newest features.

We move right on to adding the attributes we need by editing the code in edit.js:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 /** * Retrieves the translation of text. * * @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-i18n/ */ import { __ } from '@wordpress/i18n'; /** * React hook that is used to mark the block wrapper element. * It provides all the necessary props like the class name. * * @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-block-editor/#useblockprops */ import { __experimentalLinkControl as LinkControl, AlignmentToolbar, BlockControls, MediaUpload, RichText, useBlockProps, } from '@wordpress/block-editor'; import { Button, ToolbarButton, Popover } from '@wordpress/components'; import { useRef, useState } from '@wordpress/element'; import { link } from '@wordpress/icons'; /** * Lets webpack process CSS, SASS or SCSS files referenced in JavaScript files. * Those files can contain any CSS code that gets applied to the editor. * * @see https://www.npmjs.com/package/@wordpress/scripts#using-css */ import './editor.scss'; /** * The edit function describes the structure of your block in the context of the * editor. This represents what the editor will render when the block is used. * * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#edit * * @return {WPElement} Element to render. */ export default function Edit({ attributes, setAttributes, isSelected }) { const { alignment, title, mediaID, mediaURL, description, ctaLabel, sectionLink } = attributes; const isURLSet = !! sectionLink; const blockProps = useBlockProps(); const [ isEditingURL, setIsEditingURL ] = useState( false ); const [ popoverAnchor, setPopoverAnchor ] = useState( null ); const richTextRef = useRef(); const onChangeAlignment = ( newAlignment ) => { setAttributes( { alignment: newAlignment === undefined ? 'none' : newAlignment, } ); }; const onChangeTitle = ( newTitle ) => { setAttributes( { title: newTitle } ); }; const onSelectImage = ( newMedia ) => { setAttributes( { mediaURL: newMedia.url, mediaID: newMedia.id, } ); }; const onChangeDescription = ( value ) => { setAttributes( { description: value } ); }; const onChangeCTALabel = ( newCtaLabel ) => { setAttributes( { ctaLabel: newCtaLabel } ); }; function startEditing( event ) { event.preventDefault(); setIsEditingURL( true ); } const onChangeSectionLink = ( newSectionLink ) => { setAttributes( { sectionLink: newSectionLink } ); }; console.log( 'sectionLink: ', sectionLink ); return ( <div { ...blockProps }> { attributes.title && ! isSelected ? ( <> <p>{ __( 'Project alignment', 'headstartwp' ) + ': ' + alignment }</p> <p>{ __( 'Project title', 'headstartwp' ) + ': ' + title }</p> <p>{ __( 'Project mediaID', 'headstartwp' ) + ': ' + mediaID }</p> <p>{ __( 'Project mediaURL', 'headstartwp' ) + ': ' + mediaURL }</p> <p>{ __( 'Project description', 'headstartwp' ) + ': ' + description }</p> <p>{ __( 'Project CTA label', 'headstartwp' ) + ': ' + ctaLabel }</p> <p>{ __( 'Project section link', 'headstartwp' ) + ': ' + sectionLink?.url || '' }</p> </> ) : ( <> <BlockControls> <AlignmentToolbar value={ alignment } onChange={ onChangeAlignment } /> <ToolbarButton name="link" icon={ link } title={ __( 'Link' ) } onClick={ startEditing } /> </BlockControls> { isSelected && ( isEditingURL || isURLSet ) && ( <Popover placement="bottom" onClose={ () => { setIsEditingURL( false ); richTextRef.current?.focus(); } } anchor={ popoverAnchor } focusOnMount={ isEditingURL ? 'firstElement' : false } __unstableSlotName={ '__unstable-block-tools-after' } shift > <LinkControl className="wp-block-navigation-link__inline-link-input" value={ sectionLink } onChange={ onChangeSectionLink } onRemove={ () => { unlink(); richTextRef.current?.focus(); } } forceIsEditingLink={ isEditingURL } /> </Popover> ) } <div className="title"> <h3>{ __( 'Title', 'headstartwp' ) }</h3> <RichText placeholder={ __( 'Project title', 'headstartwp' ) } value={ title } onChange={ onChangeTitle } /> </div> <div className="image"> <h3>{ __( 'Image', 'headstartwp' ) }</h3> <MediaUpload onSelect={ onSelectImage } allowedTypes="image" value={ mediaID } render={ ( { open } ) => ( <Button className={ mediaID ? 'image-button' : 'button button-large' } onClick={ open } > { ! mediaID ? ( __( 'Upload Image', 'headstartwp' ) ) : ( <img src={ mediaURL } alt={ __( 'Upload Project Image', 'headstartwp' ) } /> ) } </Button> ) } /> </div> <div className="description"> <h3>{ __( 'Description', 'headstartwp' ) }</h3> <RichText placeholder={ __( 'Project description', 'headstartwp' ) } value={ description } onChange={ onChangeDescription } className="description" /> </div> <div className="ctaLabel"> <h3>{ __( 'CTA label', 'headstartwp' ) }</h3> <RichText placeholder={ __( 'Project CTA label', 'headstartwp' ) } value={ ctaLabel } onChange={ onChangeCTALabel } className="ctaLabel" /> </div> </> ) } </div> ); }

The save.js, on the other hand, will be extremely simple:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 /** * React hook that is used to mark the block wrapper element. * It provides all the necessary props like the class name. * * @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-block-editor/#useblockprops */ import { useBlockProps } from '@wordpress/block-editor'; /** * The save function defines the way in which the different attributes should * be combined into the final markup, which is then serialized by the block * editor into `post_content`. * * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#save * * @return {WPElement} Element to render. */ export default function save( { attributes } ) { const blockProps = useBlockProps.save( { attributes: attributes }); return ( <div { ...blockProps }></div> ); }

One of the nicest things about Gutenberg is having the blocks aesthetically formatted as we would have them in production. That’s not going to be the case right now, but as soon as we write the code for the frontend we’re going to bring it back to the backend as well to make up for that flaw. Let’s open a page immediately, choose our new block and fill in all the inputs.

When saved, this will be the result:

Inspecting the page at the frontend, we will find our block with all the data we entered at the backend, ready for use in the data-wp-block:

If you are eager to know how to proceed and want to complete the work, read this other article https://blog.riccardodicurti.it/headstartwp-add-a-form-with-contact-form-7 where we create a component for HeadstartWP or wait for the release of part two where we will proceed together.

Published: 7/19/2023

Did you find what you read useful?

I truly hope that I have been able to provide you with valuable and helpful information. If you still need assistance or have specific questions regarding topics covered in the blog, don't hesitate to write to me. I am available to offer you personalized consulting tailored to your needs.