Last active
November 18, 2024 18:33
-
-
Save gaambo/633bcd83a9596762218ffa65d0cfe22a to your computer and use it in GitHub Desktop.
ACF Block with Innerblocks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Fragment } from "@wordpress/element"; | |
import { InnerBlocks } from "@wordpress/editor"; | |
/** | |
* Changes the edit function of an ACF-block to allow InnerBlocks | |
* Should be called like this on `editor.BlockEdit` hook: | |
* ` addFilter("editor.BlockEdit", "namespace/block", editWithInnerBlocks("acf/block-name"));` | |
* | |
* @param {string} blockName the name of the block to wrap | |
* @param {object} innerBlockParams params to be passed to the InnerBlocks component (like allowedChildren) | |
*/ | |
const editWithInnerBlocks = ( | |
blockName, | |
innerBlockParams, | |
append = true, | |
hideBlockEdit = false | |
) => BlockEdit => props => { | |
if (props.name !== blockName) { | |
return <BlockEdit {...props} />; | |
} | |
if (append) { | |
return ( | |
<Fragment> | |
{!hideBlockEdit && <BlockEdit {...props} />} | |
<InnerBlocks {...innerBlockParams} /> | |
</Fragment> | |
); | |
} | |
// put before block edit | |
return ( | |
<Fragment> | |
<InnerBlocks {...innerBlockParams} /> | |
{!hideBlockEdit && <BlockEdit {...props} />} | |
</Fragment> | |
); | |
}; | |
/** | |
* Changes the save function of an ACF-block to allow InnerBlocks | |
* Should be called like this on `blocks.getSaveElement` hook: | |
* `addFilter("blocks.getSaveElement", "namespace/block", saveWithInnerBlocks("acf/block-name"));` | |
* | |
* @param {string} blockName the name of the block to wrap | |
*/ | |
const saveWithInnerBlocks = blockName => (BlockSave, block) => { | |
if (typeof block === "undefined") { | |
return BlockSave; | |
} | |
if (block.name !== blockName) { | |
return BlockSave || block.save; | |
} | |
return ( | |
<div> | |
<InnerBlocks.Content /> | |
</div> | |
); | |
}; | |
export { editWithInnerBlocks, saveWithInnerBlocks }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FYI: ACF 5.9 will support innerBlocks: https://www.advancedcustomfields.com/blog/acf-5-9-exciting-new-features/