Make Image & Gallery blocks default to wide alignment

in

I wanted to make image & gallery blocks in the Gutenberg block editor default to using a wide alignment. With the way my theme is designed I always want for images I add to be set with a wide width so they extend wider than the central column of text. Same with image galleries. So I started looking around on the net to see if I could figure out how I could extend Gutenberg to make it default to the settings I wanted.

After trying several methods mentioned on various websites I was finally able to find one article that got me where I wanted to go. If you want to try it here yo go:

Step 1: Enqueue a JS file into the Editor

Adding the following code into the functions.php file of your theme will make it so WordPress looks to load a file called block-editor-settings.js when you are editing a post or page.

// Load JS for Gutenberg settings 
add_action( 'enqueue_block_editor_assets', 'my_editor_assets', 100 );

function my_editor_assets() {
  $js_dir = get_stylesheet_directory_uri() . '/js';

  wp_enqueue_script( 'my-editor', $js_dir . '/block-editor-settings.js',
    [ 'wp-blocks', 'wp-dom' ] , '', true );
}

Step 2: Change alignment default on Image & Gallery blocks

You will now need to create a file called block-editor-settings.js and upload it into a folder called js in your WordPress theme directory. Inside that file you need to add the following code:

// Modify settings for Core blocks
wp.hooks.addFilter( 'blocks.registerBlockType',
  'my/change_alignment', ( settings, name ) => {

  switch( name ) {
    // Default to Wide
    case 'core/gallery':
    case 'core/image':
      return lodash.assign( {}, settings, {
        
        attributes: lodash.assign( {}, settings.attributes, { align: {
          type: 'string', default: 'wide'
        } } ),
      } );
  }

  return settings;
});

Step 3: Enjoy!

That’s all it takes. Now when adding images or galleries they will default to a wide width alignment.