Programmatically resize Gutenberg block editor preview

The WordPress block editor allows us, the editors, to resize the view by accessing the “Preview” options from the top-right toolbar.

That’s a cool option that lets us know how the content will look on different devices.

But what happens if we want to do this programmatically? What if we want to switch between different devices using the code only? There are many reasons why you’ll want to do this. Which are not the reason to discuss them here.

Easy-peasy, let’s get to work and show some code. But before we start, I must note that the code differs between the post editor and the site editor.

  • Post Editor — the editor that we use when we edit the content of posts, pages, and other CPTs.
  • Site Editor — the editor that we use when editing the site layout.

Resize the post editor programmaticaly

This will resize the post editor to Tablet mode:

wp.data.dispatch('core/edit-post').__experimentalSetPreviewDeviceType('Tablet');

If you want to access the current mode value use this code:

wp.data.select('core/edit-post').__experimentalGetPreviewDeviceType();

It will return Tablet

Resize the site editor programmaticaly

This will resize the site editor to Tablet mode:

wp.data.dispatch('core/edit-site').__experimentalSetPreviewDeviceType('Tablet');

If you want to access the current mode value use this code:

wp.data.select('core/edit-site').__experimentalGetPreviewDeviceType();

It will return Tablet

Quick tip:

You can run these lines of code in the Developer console and the results will show up instantly.

Happy coding! 🙂

Member since January 2, 2019

As a seasoned WordPress developer with expertise in various tech stacks and languages, I bring years of experience to every project I handle. My passion for coding and dedication to delivering exceptional work ensures that each project I take on is of the highest quality. I specialize in creating custom themes, developing plugins, and building full-scale web systems. By staying up-to-date with the latest industry trends and best practices, I incorporate cutting-edge solutions into my work.

Comments

    Your email address will not be published. Required fields are marked *