How can I fire a jQuery event once getBlocks() actually returns the post’s blocks instead of null?


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."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. 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?

in progress 0
MadtownLems 1 year 2021-07-28T13:25:37-05:00 0 Answer 0 views 0

Answer ( 1 )


    You need to “subscribe” to changes (see this issue) with

    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 user/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

Leave an answer