Cannot use saved attribute to the core/template-part block in Gutenberg in front end ( WP 6.2)

103 Views Asked by At

I'm building a block theme in Wordpress.

I'm trying to use a saved custom attribute to modify an existing core block using the blocks.getSaveContent.extraProps hook. Specifically, I'm trying to apply this attribute to the core/template-part block. While this approach works flawlessly for other blocks, I'm encountering issues when trying to apply it to the front-end render of the core/template-part block.

Although I'm able to save the attribute and use it to add a class to the block in the editor, I'm unable to apply it to the front-end. In fact, when attempting to log the blockTypes in the site-editor, the core/template-part block is not logged as part of the blocks rendered on the site-editor.

Using the blocks.getSaveElement hook, I'm able to obtain the element and blockType for core/template-part. However, I'm not able to add the saved value as a class on the front-end core/template-part block, as it's not passed with the attrs.

Do you have any ideas on how to add this attribute as a class to the core/template-part block on the front-end? Is it possible to hook onto the existing wrapping element using getSaveElement?

Here's the code for the save part of the script:

/**
 * Save
 */
const saveTemplatePartAttributes = ( extraProps, blockType, attributes ) => {
    console.log(blockType.name)
    
    if ( enableSidebarControlsOnBlocks.includes( blockType.name ) ) {
        const { templatePartAttributes } = attributes;
        if ( templatePartAttributes ) {
            extraProps.className = classnames( extraProps.className, 'has-' + templatePartAttributes )
        }
    }    

    return extraProps;

};
wp.hooks.addFilter(
    'blocks.getSaveContent.extraProps',
    'btt-core/save-template-part-attributes',
    saveTemplatePartAttributes
);
0

There are 0 best solutions below