Skip to content

Instantly share code, notes, and snippets.

@jeremypetrequin
Created April 17, 2020 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremypetrequin/672807361fa6919d597cdbb20b0f67ac to your computer and use it in GitHub Desktop.
Save jeremypetrequin/672807361fa6919d597cdbb20b0f67ac to your computer and use it in GitHub Desktop.
To be abble to transform gutenberg core block into ACF custom block
window.F = window.F || {}; //your custom namespace
//prepare yours transformers
window.F.blocks = {
transformParagraphToQuestion(attributes) { //the transform name you write un your PHP
//very ugly, maybe ask to ACF is there is a better option?
let interval = setInterval(() => { //we wait for the ACF block fields to be ready in the DOM
//your ACF field key in the block
//mine is a wysiwyg field, so I look for an iframe, but else you can simply look for the input you want
let $iframe = document.querySelector('[data-key="field_5e579284bf0a2"] iframe');
let iframeDoc = null;
if($iframe && (iframeDoc = ($iframe.contentDocument || $iframe.contentWindow.document)) && iframeDoc.readyState === 'complete') {
iframeDoc.body.innerHTML = attributes.content; //striptag it if needed
clearInterval(interval);
}
}, 100);
//the block you want to create
return wp.blocks.createBlock('acf/question');
}
};
//then we need to convert the string transformParagraphToQuestion passed by the PHP into a reference to our function
//we use the hook blocks.registerBlockType
wp.hooks.addFilter('blocks.registerBlockType', 'acf', (settings) => {
if(settings.name.indexOf('acf/') === 0 && settings.transforms) { //we check we are on an ACF field
['from', 'to'].forEach(key => {
let transforms = settings.transforms[key] || null;
if(!transforms) return;
transforms.forEach((transform, index) => { //if this block have transforms, we check if the function exists and we replace it
if(transform.transform && window.F.blocks[transform.transform]) {
settings.transforms[key][index].transform = F.blocks[transform.transform];
}
})
});
}
return settings;
}
);
//Et voilà
$block = [];//@see https://www.advancedcustomfields.com/resources/acf_register_block_type/
$block['transforms'] = [
'from' => [[
'type' => "block",
'isMultiBlock'=> false,
'blocks'=> ["core/paragraph", 'core/heading'],
'transform' => "transformParagraphToQuestion"
]],
];
acf_register_block($block);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment