2

In the editor, I am trying to loop through all the current post's blocks as soon as everything is loaded and ready for me.

wp.data.select("core/block-editor").getBlocks();

is able to successfully get all the blocks if I call it manually (via a link/button), but I'd like to have it run automatically.

When that snippet is inside of domReady, a la

wp.domReady( function() {...

getBlocks always returns null.

I also tried using this Promise

wp.domReady( function() {

window._wpLoadBlockEditor.then( function() {

console.log( "_wpLoadBlockEditor Promise resolved" );

var blocks = wp.data.select("core/block-editor").getBlocks();
console.log( blocks );

});

} );

But even it returns null for blocks. It makes me wonder if the Promise is only for the Editor itself being ready; not the actual post content?

If I add a two second delay (via setTimeout), then getBlocks returns all my blocks. Obviously, I don't want to wait an arbitrary amount of time and hope everything is ready. Is there some way I can ensure my script fires as soon as getBlocks() is ready to actually return the post's blocks?

1 Answer 1

0

You need to "subscribe" to changes (see this issue) with wp.data.subcribe.

A more modern version would have you use useSelect() to get the blocks. It will automatically update blocks if it changes (i.e. it will first return null, then an array of blocks once the API request completes).

import { useSelect } from '@wordpress/data';

const blocks = useSelect((select) => {
    return select('core/block-editor').getBlocks();
});

if (blocks && blocks.length > 0) {
    blocks.forEach((block) => {
        // Do whatever you want with the block
    });
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.