I am trying & learning to build custom block/template for Gutenberg and would like to “pre-set” CSS class for some specific block. Is it possible to add it like below?
Refer: [Template and Block][1]
For example, defined CSS class for one of the heading blockHeadStyle
:
function myplugin_register_book_post_type() {
$args = array(
'public' => true,
'label' => 'Books',
'show_in_rest' => true,
'template' => array(
array( 'core/image', array(
'align' => 'left',
) ),
array( 'core/heading', array(
'placeholder' => 'Add Author...',
'class' => 'blockHeadStyle'
) ),
array( 'core/paragraph', array(
'placeholder' => 'Add Description...',
)),
),
);
register_post_type('book', $args);
}
add_action('init', 'myplugin_register_book_post_type');
2 Answers
In case anyone is looking for an answer to this that doesn’t involve adding a filter and a bunch of extra code, you can add a className to the block directly in the template code. This is the same code that the OP used, with one small adjustment. “class” becomes “className”:
function myplugin_register_book_post_type() {
$args = array(
'public' => true,
'label' => 'Books',
'show_in_rest' => true,
'template' => array(
array( 'core/image', array(
'align' => 'left',
) ),
array( 'core/heading', array(
'placeholder' => 'Add Author...',
'className' => 'blockHeadStyle anotherClassName'
) ),
array( 'core/paragraph', array(
'placeholder' => 'Add Description...',
)),
),
);
register_post_type('book', $args);
}
add_action('init', 'myplugin_register_book_post_type');
Here is a screenshot to show how this renders in dev tools:
As you can see, I also added a second class to the h2 element, simply by adding a space between each class declared by “className.”