האתר של יוחאי

מוזמנים להכנס (:

Playing with non-JSX WP Blocks

i created custom css block, and encountered a weird error

i debugged it along chat gpt O1-preview, which didnt find the issue… and i ended up solving it myself

then i asked the chat to write a short blog post about it.

and ChatGPT wrote:


Fixing the “registerBlockType is not defined” Error in WordPress Block Development

While developing a custom Gutenberg block without JSX, I encountered the error:

Uncaught ReferenceError: registerBlockType is not defined

This error occurred only when editing posts of the custom post type wp_block. The issue was that the wp.data.subscribe function wasn’t always available in that context, causing the script to fail when wp.data was undefined.

The Problem:

In the initial code, we directly accessed wp.data.subscribe without checking if wp.data existed:

wp.data.subscribe(() => {

    // code...

});

When editing wp_block posts, the wp.data object might not be loaded, leading to the error.

The Fix:

We modified the code to safely access subscribe from wp.data and check if it exists before using it:

const { subscribe } = wp.data || {};
if (subscribe) {
    subscribe(() => {
        // code...
    });
}

By adding the conditional check if (subscribe), we ensure that the subscribe function is only called when it’s available, preventing the script from throwing an error when editing wp_block posts.

Conclusion:

This simple fix makes the custom block more robust across different post types by accounting for the varying availability of the wp.data module. Always checking for the existence of WordPress global objects before using them can prevent such issues.

References:

Developing WordPress Blocks Without JSX or a Build Process

WordPress Block Editor Handbook: Data Module Reference