6

I have set some css classes for the boxes in the Gutenberg editor, and I can type it in the additional css input box, it is not a problem for me, but for the client it is not convenient, because he does not know and he forget them. There is a way to have a drop-down with all the custom classes instead of a simple input field?

Thank you.

6

You should add a custom plugin. That's need a PHP main file that include, register a JavaScript file. The source below should result in an plugin. You find a usable solution also in the probs below.

PHP part

add_action( 'enqueue_block_editor_assets', 'my_gutenberg_scripts' );
function my_gutenberg_scripts() {

    wp_register_script(
        'my-editor-enhancement',
        plugins_url( 'editor.js', __FILE__ ),
        array( 'wp-blocks' ), // Necessary script handles.
        filemtime( plugins_url( 'editor.js', __FILE__ ) ),
        true
    );

    wp_enqueue_script( 'my-editor-enhancement' );
}

JavaScript part

In our example is this the code of the editor.js, that we enqueue above. The example add only one paragraph and two different heading types.

wp.domReady( () => {

    wp.blocks.registerBlockStyle( 'core/paragraph', {
        name: 'blue-paragraph',
        label: 'Blue Paragraph'
    } );

    wp.blocks.registerBlockStyle( 'core/heading', {
        name: 'default',
        label: 'Default',
        isDefault: true,
    } );

    wp.blocks.registerBlockStyle( 'core/heading', {
        name: 'alt',
        label: 'Alternate',
        isDefault: false,
    } );

} );

If you add isDefault: true, then this style will be marked as active on visible blocks that don’t already have a style specified.

core blocks

  • core/paragraph
  • core/image
  • core/heading
  • core/gallery
  • core/list
  • core/quote
  • core/audio
  • core/cover
  • core/file
  • core/video
  • core/preformatted
  • core/code
  • core/freeform
  • core/html
  • core/pullquote
  • core/table
  • core/verse
  • core/button
  • core/columns
  • core/media-text
  • core/more
  • core/nextpage
  • core/separator
  • core/spacer
  • core/shortcode
  • core/archives
  • core/categories
  • core/latest-comments
  • core/latest-posts

Removing blocks

JavaScript part

 wp.domReady( () => {
    wp.blocks.unregisterBlockStyle( 'core/button', 'default' );
    wp.blocks.unregisterBlockStyle( 'core/button', 'outline' );
    wp.blocks.unregisterBlockStyle( 'core/button', 'squared' );
} );

Probs

0

Finally, I find an alternative solution here: https://www.billerickson.net/block-styles-in-gutenberg/

  • 1
    I add a longer answer that helps user to get a valid answer, also if we lost the source of the link. – bueltge Mar 26 at 19:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.