Enhancing Gutenberg featured image control

The question:

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.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment