5

I have a client that wants images to automatically be centered. This used to be possible with the image_default_align option for the old editor. Is there a simple way to change the default attributes for core blocks?

3
  • Gutenberg already have a align center option that appears on toolbar. You can add your editor styles via hook for some custom styling. Mar 11, 2019 at 21:19
  • Thanks @MehmoodAhmad I know the center options is there. My clients wants center to be the default for the image block. I would like to change this default attribute.
    – Nate
    Mar 13, 2019 at 1:41
  • I think it can be achievable via Block Filters (developer.wordpress.org/block-editor/developers/filters/…), but I'm not sure. Still working on this myself. Nov 16, 2019 at 17:08

1 Answer 1

1

As it was mentioned in comments it is possible with Block Filters. Below is the code that allowes images to be automatically centered when inserted.

wp.hooks.addFilter( 'blocks.registerBlockType', 'misha/img', ( settings, name ) => {
    // so we check block name here if it is image we change attributes
    if( 'core/image' === name ) {

        return lodash.assign( {}, settings, {
            attributes: lodash.assign( {}, settings.attributes, { 
                align: {
                    type: 'string', 
                    default: 'center'
                } 
            } )
        } )
        
  }

  return settings
    
})

This code can be used in any JS file enqueued with enqueue_block_editor_assets, the code snippet I took from this guide https://rudrastyh.com/gutenberg/change-default-blocks-with-block-filters.html

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.