Media PHP Beginner

Turn On Lightbox for All Images

Make every Image block open in a full-screen lightbox when clicked, using WordPress's built-in "Expand on click" feature.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 15 lines
add_filter( 'wp_theme_json_data_theme', function ( $theme_json ) {
	return $theme_json->update_with( [
		'version'  => 3,
		'settings' => [
			'blocks' => [
				'core/image' => [
					'lightbox' => [
						'enabled'      => true,
						'allowEditing' => true,
					],
				],
			],
		],
	] );
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Since WordPress 6.4, the Image block has an “Expand on click” option that opens a lightbox with no plugin. It’s off by default and has to be turned on one image at a time. This snippet makes it the default for every image.

How it works

Block settings come from theme.json. The wp_theme_json_data_theme filter changes them from PHP, here setting the Image block’s lightbox.enabled to true, so every image opens in a lightbox unless an editor turns it off.

allowEditing keeps the option in the block toolbar so editors can switch it off for individual images.

Things to watch

  • Images that link somewhere can’t use the lightbox. The link wins.
  • Works with classic and block themes, but only for images added with the Image block.
  • The lightbox loads a small script from WordPress’s Interactivity API on pages that use it.

How to test it

View a post with an Image block and click the image. It should open full screen.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only