I think you can do this in a couple of different ways. I can’t help with the specific processing you want done (since I don’t know exactly what all you want done) but hopefully this gets you started.
Option 1
Loop through all blocks and “process” each block independently.
import { useSelect } from '@wordpress/data';
// Get the full list of blocks in the editor
const blocks = useSelect((select) => {
return select('core/block-editor').getBlocks();
});
// Loop through each block and do whatever needs doing
if (blocks.length > 0) {
blocks.forEach((block) => {
// Process the block here
});
}
You can console.log
to see what each block contains, but they are essentially just a bunch of attributes stored as an object.
You may need to recursively loop over nested blocks since Gutenberg supports InnerBlocks
.
if (block.hasOwnProperty('innerBlocks') && block.innerBlocks.length > 0) {
block.innerBlocks.forEach((innerBlock) => {
// Do your processing
});
}
Option 2
Get the full HTML content of the edited post and process it as if it were static HTML.
import { useSelect } from '@wordpress/data';
// Get the full edited post content (HTML string)
const content = useSelect((select) => {
return select('core/editor').getEditedPostContent();
});
// Parse the HTML so you can do things with it.
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(content, 'text/html');
// Do whatever with the HTML (htmlDoc) you want
// E.g. Get all the links:
const links = htmlDoc.getElementsByTagName('a');
You can add a custom button to the editor sidebar to trigger the processing like this:
import { PluginPostStatusInfo } from '@wordpress/edit-post';
import { Button } from '@wordpress/components';
registerPlugin('my-post-status-info', {
render: () => {
const doProcessing = () => {
// Do your processing
};
return (
<PluginPostStatusInfo>
<Button
isLink={ true }
onClick={ () => doProcessing }
>
{ __('Process', 'pb') }
</Button>
</PluginPostStatusInfo>
);
}
});