Adding a lightbox to WordPress without using a plugin

Do please help me adjust or improve the below lightbox codes. Thank you very much!
Here are the lightboxes I have added to this tutorial.

Colorbox
Lightbox 2
Fancybox 3
Fancybox 4 (not yet working)
glightbox (Most interesting)
simplelightbox (not yet working)
Photoswipe (not yet working)
Lightbox plugins

Some of the below lightbox scripts I have not been able to yet get working in WordPress.

Sometimes one wants more control over how features are added to the site and might select to add a script instead of a WordPress plugin. Most of the below jQuery lightboxes – popup scripts also have a WordPress plugin available.

The below JavaScript files have a similar setup that looks like this:

  • Download the project files usually from Github.
  • Add the .css, min.js and create an initilization (init) JavaScript file.
  • Enqueue the files through the functions.php file or a code plugin.
  • Go to a post/page and link the image to the media file.

Test. It might work and if not search online and let me know the solution. As I have added many lightboxes below where I am not yet been able to figure out how to get these to work.

Colorbox

–> The following instructions for Colorbox works.

After clicking the image the lightbox style I selected looked like this.

Color-Box-light-boxed-PJ
  1. Go to the Colorbox web site and download the colorbox master zip file.
  2. Take a look at the various examples and find one you want to modify. I am testing example 3.
  3. In the root of the child theme folder add a new folder and call it colorbox.
  4. Copy the images folder and the colorbox.css from the master colorbox example you want to use into the new colorbox folder.
  5. From master colorbox folder duplicate the jquery.colorbox-min.js to the new colorbox folder.
  6. Make a new js file and call it colorbox-init.js. Save it to the new colorbox folder. This file will then initialize colorbox telling it how it is to be used. Add the following code to the colorbox-init.js file:
/* Initialize jQuery Colorbox*/
jQuery(function( $ ){
 $('a[href*=".jpg"], a[href*=".jpeg"], a[href*=".png"], a[href*=".gif"]').colorbox({
    transition:'none',
    rel: 'gallery',
    opacity:.85,
 
    title: function() {
    return $(this).find('img').attr('alt');
    } 
    });
});

For additional options see: www.jacklmoore.com/colorbox/ -> Settings.

Move the new colorbox folder containing: colorbox.css, jquery.colorbox-min.js, colorbox-init.js and
the images folder into the root of your child theme.

Settings I used.
I decided not to use any transition.
Rel groups images together. This option also adds the arrows to go left and right.
Adjusted the opacity so one can see through the black background.
Title function is there so the title is added above the opened image.

In the child theme folder: functions.php file or a code plugin. Add the following.

/* Enqueue Colorbox */
add_action( 'wp_enqueue_scripts', 'enqueue_colorbox' );
function enqueue_colorbox() {
 wp_enqueue_style( 'colorbox-css', get_template_directory_uri(). '/colorbox/colorbox.css' );
 wp_enqueue_script( 'colorbox',get_template_directory_uri() . '/colorbox/jquery.colorbox-min.js', array( 'jquery' ), '', true );
 wp_enqueue_script( 'colorbox-init', get_template_directory_uri() . '/colorbox/colorbox-init.js', array( 'colorbox' ), '', true ); 
}

CSS I modified in the colorbox.css file:

#cboxOverlay {
   background:#000; 
   opacity: 0.9; 
   filter: alpha(opacity = 90); 
   cursor: zoom-out !important; /* ADDED */
}

I added the zoom-out icon which shows up when moving the cursor outside of the lightbox image. To make it clear that one can click outside to exit the lightbox.

NB! The last step. In WordPress backend, be sure to link the image to the Media File, so when clicking the image on the frontend the popup/lightbox will be seen.

Colorbox resources:
Sitepoint: adding a stylish lightbox effect to the WordPress gallery
code.tutsplus.com: quick tip integrating colorbox into the native gallery shortcode

wp_enqueue_script and style.

wp_enqueue_script( $handle, $source, $dependencies, $version, $in_footer );
wp_enqueue_style( $handle, $source, $dependencies, $version, $media );

handle: unique name for script or style.
Example:’colorbox
source: the url of the script/style.
Example: get_template_directory_uri() . ‘/colorbox/jquery.colorbox-min.js
dependencies: An array of assets the script/style depends on. Loaded before the enqueued script.
Example: array(‘jquery’)
version: A version number which will be appended to the query. To make sure that the user receives the correct version.
Example: ‘1.0.0’
in_footer:
 For loading scripts in the wp_footer() at the bottom of the page.
Example:  true

media: How the media should be displayed.
Example: screen, print. handheld etc.

Lightbox2

–> The following instructions for Lightbox 2 works.

Go to https://github.com/lokesh/lightbox2 and download the project files zip.

  • Unzip and open. Go to the dist folder.
  • Create a new folder and call it lightbox2. In this folder we will place the following.
  • Duplicate lightbox.css (from the css folder), lightbox.min.js (from the js folder) and images folder into the new lightbox2 folder.
  • Open lightbox.css and change the various mentions of the link (should be 4 links) to the images folder. An example, url(../images/loading.gif) to url(images/loading.gif) so that the various icons show up in the lightbox.

Add the following code to the functions.php file or a code plugin.

add_action( 'wp_enqueue_scripts', 'themeslug_scripts' );
function themeslug_scripts() {
wp_enqueue_style( 'lightbox', get_template_directory_uri() . '/lightbox2/lightbox.css', array(), '4.3.0' );
wp_enqueue_script( 'lightbox', get_template_directory_uri() . '/lightbox2/lightbox.min.js', array( 'jquery' ), '3.3.0', true );
}

add_filter('the_content', 'lightbox2');
function lightbox2 ( $content ) {
global $post;
$pattern = "/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";
$replacement = '<a$1 data-lightbox="post-image" href=$2$3.$4$5$6</a>';
$content = preg_replace($pattern, $replacement, $content);
//$content = str_replace("%LIGHTID%", $post->ID, $content);
return $content;
}

Code came from this Github comment: https://github.com/lokesh/lightbox2/issues/342#issuecomment-91997716
It could use an improvement to show how to use the various options that exist with lightbox2.

Fancybox 3

–> I believe I was able to get this to work.

fancyapps.com/fancybox/3/
github: /fancyapps/fancybox

The process is very similar to colorbox.

  1. Download 3.0.zip from one of the above links.
  2. Unzip and open fancybox-3.0 -> dist and copy jquery.fancybox.css and jquery.fancybox.min.js.
  3. Create a new folder (I called mine lightbox) in the root of the theme you are using. Paste in the css and js files.
  4. Create a new js file save it as jquery.fancybox-init.js.

Add the following js to the init file:

jQuery(function( $ ){
 $('a[href*=".jpg"], a[href*=".jpeg"], a[href*=".png"], a[href*=".gif"]').fancybox({
 }); 
});

An alternative to the above code.

jQuery(function( $ ){
$(‘a[href*=”.jpg”], a[href*=”.jpeg”], a[href*=”.png”], a[href*=”.gif”]’).fancybox({
selector : ‘.blocks-gallery-item figure a’
});
});

The above is the bare bones code to get it to work.

Add the following code to your functions.php file:

/* Fancybox 3 - https://fancyapps.com/fancybox/3/ */
add_action('wp_enqueue_scripts', 'enqueue_fancybox_styles');
function enqueue_fancybox_styles() {
 wp_enqueue_style('fancybox_style', get_stylesheet_directory_uri().'/lightbox/jquery.fancybox.css', array());
}
 
add_action('wp_enqueue_scripts', 'enqueue_fancybox_scripts');
function enqueue_fancybox_scripts() {
 wp_enqueue_script('fancybox_script', get_stylesheet_directory_uri().'/lightbox/jquery.fancybox.min.js', array('jquery'));
 
 wp_enqueue_script('fancybox_init_script', get_stylesheet_directory_uri().'/lightbox/jquery.fancybox-init.js', array('jquery'));
}

FancyBox WordPress plugins:
easy-fancybox and fancybox-for-WordPress

Fancybox 4

–> Not yet working.

https://github.com/fancyapps/ui
https://fancyapps.com/docs/ui/fancybox/

Go to one of the CDN links. I went to:
https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/

Right clicked and select “Save Link As…” (Download):
fancybox.css and fancybox.umd.js

I made a new folder I called fancybox. Added both files into it.

Create a new fancybox-init.js file to initialize fancybox. Add it to the fancybox folder.
I added the following code:

<script>
$(document).ready(function() {
$('.fancybox').fancybox({
padding : 0,
openEffect : 'elastic'
});
});
</script>

With the above code one will need to add the CSS class to the image it will be used with. Another approach is to add fancybox to all images:

<script>
$(document).ready(function() {
$("a[href$='.jpg'],a[href$='.jpeg'],a[href$='.png'],a[href$='.gif']").attr('rel', 'gallery').fancybox();
padding : 0,
openEffect : 'elastic'
});
});
</script>

As it seems like I am mixing up two different Github repos. In this issue I was told about the following code:

Fancybox.bind('a[href*=".jpg"], a[href*=".jpeg"], a[href*=".png"], a[href*=".gif"]') {
// Your options
});

Resource: https://github.com/Feoni4/fancybox

Add the fancybox folder containing fancybox.css, fancybox.umd.js and fancybox-init.js into the root of your child theme.
Add the following code to your functions.php file or a code plugin.

/* Enqueue Fancybox */
add_action( 'wp_enqueue_scripts', 'enqueue_fancybox' );
function enqueue_fancybox() {
wp_enqueue_style( 'fancybox-css', get_template_directory_uri(). '/fancybox/fancybox.css' );
wp_enqueue_script( 'fancybox',get_template_directory_uri() . '/fancybox/fancybox.umd.js', array( '' ), '', true );
wp_enqueue_script( 'fancybox-init', get_template_directory_uri() . '/fancybox/fancybox-init.js', array( 'fancybox' ), '', true ); 
}

In WordPress go to a post/page. Add an image and link it to the media file. Test the frontend and see if the lightbox shows up.

glightbox

https://biati-digital.github.io/glightbox/

–> Working.

https://github.com/biati-digital/glightbox

Download the zip at Github repo for glightbox and unzip it.
Create a new folder named glightbox and add it to the root of your child theme.

Open the dist folder and duplicate the following files:
glightbox.min.js and glightbox.css into the newly created glightbox folder.

Create a new init.js file and add it to the new glightbox folder.
Example code from https://github.com/biati-digital/glightbox/blob/master/README.md Lightbox Options.
Modify it to fit your needs. I added just the basic code below into the init.js file.

const lightbox = GLightbox({
touchNavigation: true,
loop: true,
autoplayVideos: true,
zoomable: true
});

Add the following Enqueue and Filtering code to the functions.php or a PHP code plugin.

/* Enqueue Glightbox */
add_action( 'wp_enqueue_scripts', 'enqueue_glightbox' );
function enqueue_glightbox() {
wp_enqueue_style( 'glightbox-css', get_stylesheet_directory_uri(). '/glightbox/glightbox.css' );
wp_enqueue_script( 'glightbox', get_stylesheet_directory_uri() . '/glightbox/glightbox.min.js', '', '', true );
wp_enqueue_script( 'glightbox-init', get_stylesheet_directory_uri() . '/glightbox/init.js', '', '', true );
}

/* Filtering. This is an alternative to using JQuery. */
add_filter('the_content', 'glightbox_class');
function glightbox_class ( $content ) {
global $post;
$pattern = "/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";
$replacement = '<a$1 class="glightbox" href=$2$3.$4$5$6>';
$content = preg_replace($pattern, $replacement, $content);
return $content;
}

NB! Be sure to link media to the Media File which you want to have opened in the lightbox.
A big thanks to Antonio with helping to get the glightbox code working!

Resources:
https://www.npmjs.com/package/glightbox
https://opensourcelibs.com/lib/glightbox

Simple Lightbox

https://simplelightbox.com/
https://github.com/andreknieriem/simplelightbox
WordPress plugin: https://wordpress.org/plugins/simple-lightbox/

–> Is not yet working.
I made this issue: https://github.com/andreknieriem/simplelightbox/issues/246

Download the Simple Lightbox Master zip file from the Github repo. (Click Code and download zip.)
Extract the simplelightbox-master.
Create a new folder called simplelightbox which will be added to the root of your child theme.
Duplicate following files from the simplelightbox-master folder -> dist:
simple-lightbox.css
and
simple-lightbox.min.js.

Create a new init.js file containing the following code:

if(document.querySelectorAll('a.simplelightbox').length ) {
    let simplelightbox = new SimpleLightbox('a.simplelightbox',{});
}

Save and add the init.js file to the new simplelightbox folder.

In the child theme functions file or a code snippet plugin add the following code.

add_filter('the_content', [$this, 'autoexpand_rel_wlightbox'], 99);
add_filter('the_excerpt', [$this, 'autoexpand_rel_wlightbox'], 99);

public function autoexpand_rel_wlightbox ($content) {
    global $post;
    $pattern     = "/(<a(?![^>]*?rel=['\"]lightbox.*)[^>]*?href=['\"][^'\"]+?\.(?:bmp|gif|jpg|jpeg|png|webp)['\"][^\>]*)>/i";
    $replacement = '$1 class="simplelightbox" rel="lightbox['.$post->ID.']">';
    $content     = preg_replace($pattern, $replacement, $content);
    return $content;
}


PhotoSwipe

https://photoswipe.com/
https://github.com/dimsemenov/PhotoSwipe

—> Is not yet working.
I made this issue: https://github.com/dimsemenov/PhotoSwipe/issues/1803

Download the PhotoSwipe-master zip at Github repo for PhotoSwipe. (To get the beta of version 5 go to: https://github.com/dimsemenov/PhotoSwipe Click the Master branch drop down and select v5 beta: https://github.com/dimsemenov/PhotoSwipe/tree/v5-beta )

Using the current version.
Create a new folder named photoswipe. Duplicate the following files inside the dist folder into the new photoswipe folder.

photoswipe.css
photoswipe-ui-default.min.js
photoswipe.min.js
and the default-skin folder with contents.

Create a new init.js file and add it to the photoswipe folder. I named the js file: photoswipe-init.js.
Add the following code:

/* Initialize PhotoSwipe */
var options = ('a[href*=".jpg"], a[href*=".jpeg"], a[href*=".png"], a[href*=".gif"]') {
// optionName: 'option value'
// for example:
index: 0 // start at first slide
};

Move the photoswipe folder into the root of the child theme you are using.
Add the following code to your child theme functions.php file or a code plugin.

/* Enqueue PhotoSwipe */
add_action( 'wp_enqueue_scripts', 'enqueue_photoswipe' );
function enqueue_photoswipe() {
wp_enqueue_style( 'photoswipe-css', get_template_directory_uri(). '/photoswipe/photoswipe.css' );
wp_enqueue_script( 'photoswipe',get_template_directory_uri() . '/photoswipe/photoswipe.min.js', array( '' ), '', true );
wp_enqueue_script( 'photoswipe ui default',get_template_directory_uri() . '/photoswipe/photoswipe-ui.default.min.js', array( '' ), '', true );
wp_enqueue_script( 'photoswipe-init', get_template_directory_uri() . '/photoswipe/photoswipe-init.js', array( 'photoswipe' ), '', true ); 
}

I hope to also add a working version of  fslightbox.com to this tutorial, along with a bunch of other working lightbox examples as well.

I have also been testing out Fast Image Zoom Github project.
It should be a simple one to add but it is not working for me yet.

A search on lightbox at wordpress.org plugins section:

https://wordpress.org/plugins/wp-video-lightbox/
https://wordpress.org/plugins/responsive-lightbox/

https://wordpress.org/plugins/foobox-image-lightbox/
https://wordpress.org/plugins/wp-lightbox-2/
https://wordpress.org/plugins/wp-jquery-lightbox/

https://huge-it.com/lightbox/

wordpress.transformnews.com/tutorials/how-to-implement-fancybox-in-wordpress-creating-your-own-plugin-84
https://wpdatatables.com/wordpress-lightbox-plugins-you-should-know-of/

github.com/blueimp/Gallery

This tutorial was originally written 6 September 2014.

Share the article:

6 Comments

  1. Thanks a lot for your post – I just installed glightbox.
    I had to ad avif as image format to the pattern in order to make it work – now, it looks great!

    • Good to hear!
      Do add any tips or ways you added glightbox to get your version to work.
      As it is always good to have additional methods to share to this post.
      Thank you for your feedback!

Leave a Reply

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