Wordpress 6.6 theme: Add Photoswipe attributes to image links: data-pswp-width, data-pswp-height

raw

functions.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
function mytheme_register_image_block_render_callback($args, $name)
{
    if ($name === 'core/image') {
        $args['render_callback'] = 'mytheme_render_image_photoswipe';
    }
    return $args;
}
 
/**
 * Add extra attributes to the large image link so that Photoswipe
 * can scale the images correctly
 */
function mytheme_render_image_photoswipe($attributes, $content, $block)
{
    if ($attributes['linkDestination'] != 'media'
        || !isset($attributes['id'])
        || $attributes['id'] === ''
    ) {
        return $content;
    }
 
    $img_meta = wp_get_attachment_metadata($attributes['id']);
    if ($img_meta === false) {
        return $content;
    }
 
    $newAttrs = 'data-pswp-width="' . $img_meta['width'] . '"'
        . ' data-pswp-height="' . $img_meta['height'] . '"';
    $content = str_replace('<a ', '<a ' . $newAttrs . ' ', $content);
 
    return $content;
}
 
add_filter(
    'register_block_type_args',
    'mytheme_register_image_block_render_callback', 10, 2
);
 
Christian Weiske Christian Weiske
owner

History