How To Automatically Set Image Alignment In WordPress Block Editor

When you use the WordPress block editor a lot, you may wish you could automatically set the image alignment when you add a new image.

By default, the image will have an alignment of "None".

Adding an image to the WordPress block editor with none set as the alignment

How to automatically center images in the WordPress block editor

To have the images automatically be center-aligned when you add them to the WordPress block editor, add this code to the functions.php file of your child theme.

add_filter( 'block_type_metadata', 'set_image_auto_centre' );

function set_image_auto_centre( $metadata ) {
  if ( 'core/image' !== $metadata['name'] ) {
    return $metadata;
  }
  $metadata['attributes']['align']['default'] = 'center';

  return $metadata;
}

Once you've implemented this code, adding a new image will have its alignment set to center.

Adding an image to the WordPress block editor with align center automatically set

The way this works is whenever a block is called, it checks against our function.

We have a guard clause to stop processing if it's any block other than the normal image block:

if ( 'core/image' !== $metadata['name'] ) {
  return $metadata;
}

If the function is still running at this point, we know we're working with the image block.

We change the default to center with:

$metadata['attributes']['align']['default'] = 'center';

And return the result to the block editor.

You don't have to stick with center alignment. You could do:

  • wide
  • full
  • center
  • left
  • right

Just replace 'center' with the alignment that suits your workflow.

To use wide or full, your theme will need to support wide and full width images.

As this is PHP, you can run conditionals, so maybe check if it's a page or a post. Maybe you want the default image to be wide on a particular custom post type.

Does changing the default alignment force all images to the same alignment?

This code will only change the default - how the image is brought in.

If you want to change the alignment after, that's no problem.

All you're doing is changing the alignment to center instead of none, which is the default.

Mike Haydon

Thanks for checking out my WordPress and coding tutorials. If you've found these tutorials useful, why not consider supporting my work?

Buy me a coffee

Leave a Comment