WordPress 6.4 invented a new feature "expand on click" which opens an integrated lightbox for images in certain Gutenberg blocks. Lightbox with PhotoSwipe could optionally override the rendering for the core image block this to output the image as a linked image.
A solution fragment suggested by Taeo - this works to some extend, but still lacks a number of things done for regular images (EXIF data, caption handling etc.):
/**
* Overrides render callback for core image block.
*
* @param array $args An array of block parameters
* @param name $name The name of the block including namespace
* @return array
*/
function override_core_image_block_render_callback( $args, $name ) {
if ( 'core/image' === $name ) {
unset( $args['viewScript'] );
unset( $args['view_script_handles'] );
$args['render_callback'] = 'render_image_lightbox';
}
return $args;
}
add_filter( 'register_block_type_args', 'override_core_image_block_render_callback', 10, 2 );
/**
* Wrap images in links to trigger the PhotoSwipe plugin.
*
* @param array $attributes An array of block attributes
* @param string $content The HTML content of the block
* @param object $block The block object
* @return bool|array
*/
function render_image_lightbox( $attributes, $content, $block ) {
if ( false === stripos( $content, '<img' ) ) {
return '';
}
$link_destination = isset( $attributes['linkDestination'] ) ? $attributes['linkDestination'] : 'none';
$lightbox_settings = block_core_image_get_lightbox_settings( $block->parsed_block );
/*
* If the lightbox is enabled and the image is not linked, wrap the image in a link to trigger the PhotoSwipe Lightbox plugin.
*/
if (
isset( $lightbox_settings ) &&
'none' === $link_destination &&
isset( $lightbox_settings['enabled'] ) &&
true === $lightbox_settings['enabled']
) {
$img_src = wp_get_attachment_url( $attributes['id'] );
$img_meta = wp_get_attachment_metadata( $attributes['id'] );
if ( $img_src && $img_meta ) {
$pattern = '/<img.*?>/';
$replacement = sprintf( '<a class="lightbox" href="%s" data-pswp-width="%d" data-pswp-height="%d">$0</a>', esc_url( $img_src ), esc_attr( $img_meta['width'] ), esc_attr( $img_meta['height'] ) );
$content = preg_replace( $pattern, $replacement, $content );
}
}
return $content;
}
Also see here: https://wordpress.org/support/topic/support-for-new-expand-on-click-option-for-images-added-in-wp-6-4/
WordPress 6.4 invented a new feature "expand on click" which opens an integrated lightbox for images in certain Gutenberg blocks. Lightbox with PhotoSwipe could optionally override the rendering for the core image block this to output the image as a linked image.
A solution fragment suggested by Taeo - this works to some extend, but still lacks a number of things done for regular images (EXIF data, caption handling etc.):