Advanced Tutorials

WordPress Gallery Overlay with Fancybox

Do you want to add some style and make your WordPress galleries more user-friendly. Your theme doesn't support Lightbox or Fancybox, and you don't want to use a plugin just for this feature.

Do you want to add some style and make your WordPress galleries more user-friendly?

Your theme doesn’t support Lightbox or Fancybox, and you don’t want to use a plugin just for this feature?

You can do that with just several PHP and JS code lines by using Fancybox from Fancyapps.

Note: If you use this for commercial purposes, you need to get a proper license.

Download the dist/ files

If you go to the library GitHub repository, you can see all the available src & dist files.

Go into the dist/ folder and download both. fancybox.css & fancybox.umd.js Into your theme assets directory.

The JavaScript

In the example below, the fancybox CSS file is located inside assets/css and JS file inside assets/js within your main theme directory.

Add another file inside assets/js, name it main.js and add the following code:

(function($, undefined) {
  $.each($('.gallery'), function (idx, gallery) {
    $(gallery).find('a').attr('data-fancybox', $(gallery).attr('id'));
  $.each($('.blocks-gallery-item'), function (idx, gallery) {
    $(gallery).find('figure').attr('data-fancybox', 'gallery-0');

This will automatically add the proper fancybox attribute for galleries created via the Classic and Gutenberg block editors.


Now go to your theme (or child theme) functions.php find the place where all the scripts & styles are added, or add the following code inside that file.

add_action('wp_enqueue_scripts', 'fancybox_enqueue_styles_and_scripts');
function fancybox_enqueue_styles_and_scripts() 
  $theme = wp_get_theme();
  wp_enqueue_style('my-theme-fancybox', get_template_directory_uri() . '/assets/css/fancybox.css', array(), $theme->get('Version'));
  wp_enqueue_script('my-theme-fancybox', get_template_directory_uri() . '/assets/js/fancybox.umd.js', array(), $theme->get('Version'), true);
  wp_enqueue_script('my-theme-main', get_template_directory_uri() . '/assets/js/main.js', array('jquery'), $theme->get('Version'), true);

Note: if you are using a child theme, use get_stylesheet_directory_uri() instead of get_template_directory_uri().

And voila, you have integrated Fancybox, and now your galleries are much more user-friendly.

What’s Next

If you want to add Fancybox for single images (not galleries), you need to add the attribute to the

For example, when in the Classic editor, go to HTML mode:

<a href="..." data-fancybox>
  <img src="..." alt="..." width="..." height="..." class="alignnone size-large ... " />

And this is how you load and integrate Fancybox into your WordPress theme.

‘Til the next time.

Leave a Reply

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