1. Home
  2. Knowledge Base
  3. FAQ
  4. How to open images in a lightbox?

How to open images in a lightbox?

You can use the oum_location_bubble_image hook to manipulate the output of the location image. This allows you to add a lightbox feature, for example.

Example: Lightbox with WP Featherlight

I would recommend using the WP Featherlight plugin to get a lightbox effect on images. And with the following PHP script (add it to your theme’s functions.php or use a Code Snippet plugin) you can enable the lightbox effect for the location images. It adds the data-featherlight=”image” attribute to the images.

PHP
add_filter('oum_location_bubble_image', function ($image, $location) {
    // Define the data attribute to be added
    $data_attribute = 'data-featherlight="image"';

    // Add the data attribute to images that do not already have it
    $image = preg_replace('/<img(?![^>]*data-featherlight=)([^>]+)>/', '<img$1 ' . $data_attribute . '>', $image);

    return $image;
}, 10, 2);

Example: Add a custom class to images

PHP
add_filter('oum_location_bubble_image', function ($image, $location) {
    // Define the class to be added
    $custom_class = 'lightbox';

    // Add the custom class to images that already have a class attribute
    $image = preg_replace('/<img(.*?)class="([^"]*)"(.*?>)/', '<img$1class="$2 ' . $custom_class . '"$3', $image);

    return $image;
}, 10, 2);
PHP
add_filter('oum_location_bubble_image', function ($image, $location) {
    // Wrap images inside <a class="lightbox" href="image-src">
    $image = preg_replace_callback(
        '/<img([^>]*?)src=["\'](.*?)["\'](.*?)>/',
        function ($matches) {
            $imgTag = '<img' . $matches[1] . 'src="' . $matches[2] . '"' . $matches[3] . '>';
            return '<a class="lightbox" href="' . $matches[2] . '">' . $imgTag . '</a>';
        },
        $image
    );

    return $image;
}, 10, 2);
Was this article helpful?

Related Articles


EN