0

I'm wanting to add some functionality to the featured image block in the Gutenberg editor. There are a handful of posts online about how to do this, including a question/answer here on StackExchange (3rd item).

Unfortunately, I'm missing something somewhere because I can't get even the basics to work for me. I've got javascript that verifiably loads on the post type edit page as follows:

window.addEventListener("load", function(event){
  console.log("featured_image.js loaded and functional...");
});

var el = wp.element.createElement;

function wrapPostFeaturedImage( OriginalComponent ) {
  return function( props ) {
      return (
          el(
              wp.element.Fragment,
              {},
              'Prepend above',
              el(
                  OriginalComponent,
                  props
              ),
              'Append below'
          )
      );
  }
}

wp.hooks.addFilter(
  'editor.PostFeaturedImage',
  'dsplugin/wrap-post-featured-image',
  wrapPostFeaturedImage
);

But the above is having no effect on the featured image box. I'm new to Gutenberg so I'm probably missing half a dozen things. If someone could point me in the right direction, I'd be grateful.

1 Answer 1

1

I've got JavaScript that verifiably loads on the post type edit page

But did you enqueue your script with the correct dependencies? Have you checked the browser console? Did it say something like "Uncaught TypeError: Cannot read property 'createElement' of undefined"?

The JavaScript code in the question requires the @wordpress/element and @wordpress/hooks packages, which are available as registered (JavaScript) scripts in WordPress with wp-<the package name without the @wordpress/ part> as the script handle/identifier, e.g. wp-element for @wordpress/element and wp-hooks for @wordpress/hooks, so make sure your script has at least those dependencies.

wp_enqueue_script( 'your-script', '/path/to/your-script.js', [ 'wp-element', 'wp-hooks' ] );

Or you can also use block-editor, blocks, components, etc., which its dependencies include both wp-element and wp-hooks, as a dependency for your script.

See wp_default_packages_scripts() for the other (core/Gutenberg) script handles you can use.

1
  • 1
    Well that did the trick. I had noticed the errors in the console but didn't know how to read them. Adding the dependencies you suggested solved my problem. Would have been nice if that had been mentioned in the aforementioned "tutorials". Thank you!
    – Andrew
    Mar 11, 2020 at 19:43

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.