1

I have been able to add additional classes to the core/heading block using blocks.getSaveContent.extraProps filter, however, this only adds the class on the frontend, I would also like that custom class to be applied to the block element in the editor as followed.

enter image description here

I know i can use the blocks.getBlockDefaultClassName filter but dont know if I could do that based on custom attributes assigned to the block. Any help here would be much appreciated.

2
  • Why would you want to assign a class to inner elements? Perhaps you don't need this? To style an element, this is definitely not necessary.
    – Unbywyd
    Commented Aug 26, 2020 at 6:33
  • So that I can replicate the style that is shown on the frontend for those components. e.g. the <h4> element would have a class with text-large when assigned a particular attribute. I want to be able to let the content managers to see the same style while they are editing the content using the editor. Hope that makes sense.
    – Matthew
    Commented Aug 27, 2020 at 3:16

1 Answer 1

3

You can do this with the editor.BlockListBlock filter. More info here. This allows you to do something like the following:

const withCustomAttributeClass = createHigherOrderComponent( ( BlockListBlock ) => {
    return ( props ) => {
        const { attributes } = props;
        const { yourCustomAttribute } = attributes;
        const class = yourCustomAttribute ? 'my_custom_class' : '';

        return <BlockListBlock { ...props } className={ class } />;
    };
}, 'withCustomAttributeClass' );

addFilter(
    'editor.BlockListBlock',
    'your-plugin/custom-attribute-class',
    withCustomAttributeClass
);

In the above, I am just checking if the attribute exists and then am applying a class, but you could do all sorts of more complicated things here. Note that this filter will apply the class to every block with that custom attribute. However, props contains all of the block information, so you could exclude certain blocks as needed if you wanted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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