Here’s why did you get an undefined
The function itself was defined, but the function call (wp.blocks.getBlockVariations( 'core/embed' )
) returned an undefined
because by the time that you called the function, the block/Gutenberg editor had not yet been initialized.
Hence, undefined
was returned instead of an array of block variations, because core block types like Embed had not yet been registered — and if you had called wp.blocks.getBlockTypes()
, you’d see that core/embed
is not in the list.
How to ensure your code runs properly
WordPress uses wp_add_inline_script()
to add an inline script which calls the function that initializes the editor, so you need to add the same dependency passed to wp_add_inline_script()
, which is the 1st parameter, to your script’s dependencies ( the 3rd parameter for wp_register_script()
):
-
For the block-based post editor, the dependency is
wp-edit-post
which will loadwp-includes/js/dist/edit-post.js
that defineswp.editPost.initializeEditor()
and is used to initialize the block-based post editor.See source on GitHub:
wp-admin/edit-form-blocks.php
, line 303 and line 290 -
For the block-based widgets editor, the dependency is
wp-edit-widgets
which will loadwp-includes/js/dist/edit-widgets.js
that defineswp.editWidgets.initialize()
and is used to initialize the block-based widgets editor.See source on GitHub:
wp-admin/widgets-form-blocks.php
, lines 38-46 -
For the Site Editor, the dependency is
wp-edit-site
which will loadwp-includes/js/dist/edit-site.js
that defineswp.editSite.initializeEditor()
and is used to initialize the Site Editor.See source on GitHub:
wp-admin/site-editor.php
, lines 120-128
So, just add either wp-edit-post
, wp-edit-widgets
or wp-edit-site
to your script’s dependencies, depending on the current admin page, or the editor type (post/widgets/site).
That way, the editor initialization function would already be defined and called when you call wp.blocks.getBlockVariations()
and thus, you’d get the proper result.
Working Example
$deps = array( 'wp-blocks', 'wp-dom-ready' );
global $pagenow;
// If we're on the Widgets admin page, add wp-edit-widgets to the dependencies.
if ( 'widgets.php' === $pagenow ) {
$deps[] = 'wp-edit-widgets';
// If we're on the Site Editor admin page, add wp-edit-site to the dependencies.
} elseif ( 'site-editor.php' === $pagenow ) {
$deps[] = 'wp-edit-site';
// If we're on the post/Page/CPT editing screen (e.g. at wp-admin/post.php), add
// wp-edit-post to the dependencies.
} else {
$deps[] = 'wp-edit-post';
}
wp_register_script(
'block-editor-js',
plugins_url( 'js/block-editor.js', dirname(__FILE__) ),
$deps
);
Notes
-
I used the
enqueue_block_editor_assets
action/hook to run the above code. -
The minified version of the JS files mentioned above, where the file name ends with
.min.js
, will be loaded instead when script debugging is not enabled.