HeadstartWP ”“ Crea un blocco Gutenberg personalizzato
Come sempre, andiamo controcorrente e partiamo dalla documentazione https://developer.wordpress.org/block-editor/: si può dire di tutto su WordPress, ma la sua documentazione è sicuramente ben fatta e rappresenta una miniera d’oro di informazioni.
Dopo aver studiato la documentazione, possiamo passare a questo articolo. Vedremo come creare blocchi Gutenberg all’interno di un tema e realizzeremo un blocco da utilizzare su questo blog per presentare i punti salienti nella pagina dei progetti.
Come spiegato in un articolo precedente, per la mia installazione di WordPress ho scelto un tema padre e ho creato il mio tema figlio. Facciamo un breve passo indietro: tutti i tutorial che ho visto finora sulla creazione di blocchi Gutenberg iniziavano con la creazione di un plugin, ma nel mio caso preferisco procedere direttamente all’interno del tema, poiché questi blocchi saranno utilizzati solo in questo tema specifico e saranno molto semplici.
Ho aperto il mio IDE e dal terminale ho lanciato @wordpress/create-block ( https://www.npmjs.com/package/@wordpress/create-block ) per creare un blocco iniziale che ho spostato all’interno della src/blocks/ cartella del mio tema figlio.
Ho eliminato il file .php generato automaticamente e ho spostato la registrazione del blocco all’interno del file functions.php del tema, poiché non ho bisogno di aggiungere codice PHP per questi blocchi.
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' );Con questa semplice funzione registrerò tutti i blocchi che intendo aggiungere all’interno della cartella blocks. Ribadisco che è possibile mantenere il file index.php individuale nel caso in cui sia necessario aggiungere codice PHP per i blocchi.
Ho inoltre eliminato i file `package.json` e `package-lock.json` dalla cartella del singolo blocco per spostare gli script e le dipendenze all’interno del file `package.json` del template. Poiché ci sono due script che rispondono al comando `build`, ho aggiunto un suffisso a quelli dei blocchi chiamandoli [command]-blocks.
Per verificare che tutto sia corretto, eseguite un semplice npm run build-blocks e vedrete che il codice compilato apparirà nella cartella `build` e il vostro blocco di base sarà disponibile dal backend del sito.
Personalizziamo il blocco
predefinito Il blocco generato con @wordpress/create-block
è molto semplice e dobbiamo aggiungere alcuni campi: allineamento, titolo, media, descrizione, cta e link. Procediamo quindi ad aggiungere questo frammento di codice al nostro 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"
}
},Per aggiungere i campi di input nel file edit.js, il mio consiglio è di utilizzare come riferimento quelli della block-library ( https://github.com/WordPress/gutenberg/tree/trunk/packages/block-library/src ) di Gutenberg, poiché così si ha la certezza che utilizzino sempre l’API più aggiornata. Gutenberg non è un progetto nuovo, ma ancora oggi viene costantemente aggiornato e ampliato, quindi è sempre importante dare un’occhiata alle funzionalità più recenti.
Passiamo subito ad aggiungere gli attributi di cui abbiamo bisogno modificando il codice 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>
);
}Il file `save.js`, invece, sarà estremamente semplice:
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>
);
}Una delle cose più belle di Gutenberg è che i blocchi sono formattati esteticamente proprio come li vorremmo in produzione. Al momento non sarà così, ma non appena avremo scritto il codice per il frontend, lo riporteremo anche nel backend per ovviare a questa lacuna. Apriamo subito una pagina, scegliamo il nostro nuovo blocco e compiliamo tutti i campi.
Una volta salvato, questo sarà il risultato:
Ispezionando la pagina sul frontend, troveremo il nostro blocco con tutti i dati inseriti nel backend, pronto per essere utilizzato nel data-wp-block:
Se non vedete l’ora di sapere come procedere e volete completare il lavoro, leggete quest’altro articolo https://blog.riccardodicurti.it/headstartwp-add-a-form-with-contact-form-7 in cui creiamo un componente per HeadstartWP oppure aspettate l’uscita della seconda parte, dove procederemo insieme.