Gutenberg: eigene Block-Kategorie für benutzerdefinierten Inhaltstyp definieren

ACF Pro war immer schon eine gute Investition für die Entwicklung differenziert strukturierter WordPress-Projekte. Mit der Funktion acf_register_block()
sind damit benutzerdefinierte Blöcke in kurzer Zeit einsatzbereit.
Wie machtvoll die Kombination ACF – Gutenberg ist, zeigt sich grade in einem aktuellen Projekt, das bereits mit WordPress 5.0 beta aufgesetzt wird (bis das Projekt fertig ist, wird WordPress 5.0 als stable Release verfügbar sein). Das Projekt bekommt einen benutzerdefinierten Inhaltstypen der spezielle Blöcke vorsieht, die exklusiv nur diesen Typen betreffen.
Neue Blockkategorie voransetzen
function my_plugin_block_categories( $categories, $post ) {
if ( $post->post_type !== 'my_post_type' ) {
return $categories;
}
return array_merge(
array(
array(
'slug' => 'custom-category',
'title' => 'My Custom Category'
),
),
$categories
);
}
add_filter( 'block_categories', 'my_plugin_block_categories', 10, 2 );
Code-Sprache: PHP (php)
Potentiell können einzelne oder alle Standardkategorien ausgeschlossen oder neu angeordnet werden, resp die Standardkategorien auf im Inhaltstyp erwünschte beschränkt.
Die Standardkategorien sind
- common
- formatting
- layout
- widgets
- embed
function my_plugin_block_categories( $categories, $post ) {
if ( $post->post_type !== 'my_post_type' ) {
return $categories;
}
return array(
array(
'slug' => 'custom-category',
'title' => 'My Custom Category'
),
array(
'slug' => 'common',
'title' => 'Allgemeine Blöcke'
),
array(
'slug' => 'formatting',
'title' => 'Formattierung'
),
);
}
add_filter( 'block_categories', 'my_plugin_block_categories', 10, 2 );
Code-Sprache: PHP (php)
Einen oder mehrere ACF-Blöcke registrieren
function custom_block_acf_init() {
// check function exists
if( function_exists('acf_register_block') ) {
acf_register_block(array(
'name' => 'my-custom-block',
'title' => __('My Custom Block'),
'description' => __('My custom block description'),
'render_callback' => 'custom_block_render_callback',
'category' => 'custom-category',
'keywords' => array( 'some', tags' ),
));
}
}
add_action('acf/init', 'custom_block_acf_init');
Code-Sprache: PHP (php)
Templates einbinden (hier in einem Plugin, kann auch ein Theme sein)
function custom_block_render_callback( $block ) {
// convert name ("acf/my-custom-block") into path friendly slug
$slug = str_replace('acf/', '', $block['name']);
if( file_exists( plugin_dir_path( __FILE__ ) . "templates/block/content-{$slug}.php") ) {
include( plugin_dir_path( __FILE__ ) . "templates/block/content-{$slug}.php" );
}
}
Code-Sprache: PHP (php)