Add custom class to core blocks in Gutenberg

Question

I’m trying to add a class to list blocks (core/list) in Gutenberg. Unfortunately, it looks like because some blocks like lists and paragraphs don’t have the standard default class name of wp-block-{name} they can’t be renamed using the blocks.getBlockDefaultClassName filter.

To get around that, I’ve used the blocks.getSaveContent.extraProps filter, which seems to enable me to add a class to ALL the blocks that don’t already have classes. Code below is how I got that working. It’s adding added-class-name to blocks likes lists and paragraphs and so on.

function addBlockClassName( className ) {
  return Object.assign( className, { class: 'added-class-name' } );
}

wp.hooks.addFilter(
  'blocks.getSaveContent.extraProps',
  'gdt-guten-plugin/add-block-class-name',
  addBlockClassName
);

And I’m enqueuing it like so:

function gdt_blocks_class_rename() {
  wp_enqueue_script(
      'gdt-plugin-blacklist-blocks',
      get_stylesheet_directory_uri() . '/dist/guten-addons.js',
      array( 'wp-blocks' )
  );
}
add_action( 'enqueue_block_editor_assets', 'gdt_blocks_class_rename' );

However, what I want to be able to do is add a class to ONLY list blocks? Can that be done at all?

0
Trevor 4 months 0 Answers 19 views 0

Leave an answer