0
votes

In working with WordPress Gutenberg blocks, I have added custom styles to existing blocks – for instance, a boxed version of the blockquote – using block filters (register_block_style()). This is neat because it lets editors click through the visual editor without programming knowledge which secretly adds custom classes.

However, I have a dependency: if the class is-style-box-quote has been added, small-content-width must also be present.

Is there any way to add it programmatically? Perhaps when saving the post? Which hook/filter do I use for that?


(After some research and trying)

If I get the part I want to edit via save_post() (and then $post['post_content']) I get a long HTML string. Like so:

[…]
<!-- wp:quote {"className":"is-style-box-quote"} -->
<blockquote class="wp-block-quote is-style-box-quote"><p>Lorem ipsum dolor sit amet.</p></blockquote>
<!-- /wp:quote -->
[…]

Modifying that via regex would be possible, but a huge pain in the neck. Is there an established preferable way to update the classes in the DB?

1

1 Answers

0
votes

I don't see a blockquote block, so I am going to guess that it is a custom block. The following example is for a quote block.

import { assign } from 'lodash';

addFilter(
    'blocks.getSaveContent.extraProps',
    'core/quote',
    ( props ) => {

        if( props.className.contains( 'is-style-large' ) )
        {
            assign( props, { className : props.className + " small-content-width" } );
        }
    }
);

Here is the documentation for the filter: https://developer.wordpress.org/block-editor/developers/filters/block-filters/#blocks-getsavecontent-extraprops

What I would suggest doing is not editing an existing style and adding your own custom block style. This way the default will remain how it was intended.

import { registerBlockType } from '@wordpress/blocks';
import { domReady} from '@wordpress/dom-ready';

domReady( () => {
    registerBlockStyle( 'core/quote', [ 
            {
                name: 'my-custom-block-style',
                label: 'The label',
            }
        ]);
    } );
} );

Here is the documentation for adding your own block style to an existing block: https://developer.wordpress.org/block-editor/developers/filters/block-filters/#block-style-variations