Wordpress - How do i add class="fancybox" to the default gallery?

You can use javascript/jquery to solve this.

When you insert a gallery in a wordpress posts, the whole gallery is wrapped by a div with id like "gallery-1" but also a class that's always "gallery". Also, every item is surrounded by two other "dl" and "dt", with class "gallery-item" and "gallery-icon" respectively.

So, you can just use jquery to match every link inside those classes, and add whatever lightbox script you want.

If it's fancybox, i think something like this should work:

jQuery(".gallery-icon a").fancybox();

You can be more specific, matching css classes .gallery .gallery-item .gallery-icon in that order and then the a (for the link).

For the new Gutenberg galleries, this should work:

jQuery(".wp-block-gallery .blocks-gallery-item a").fancybox();  

If you want users can navigate between images as a gallery, then use:

jQuery(".gallery-icon a").fancybox().attr('data-fancybox', 'gallery');

And for the new Gutenberg galleries, use this instead:

jQuery(".wp-block-gallery .blocks-gallery-item a").fancybox().attr('data-fancybox', 'gallery');

If you want more grained control (for multiple galleries on the same page), check this response.

Or use a simple plugin that use the same approach from Viper007Bond, that does clean and nicely, but using colorbox instead.


jQuery(".gallery-icon a").fancybox().attr('data-fancybox', 'wp-gallery-fancybox');

Gives all links the same rel attribute, this way the user will be able to slide between the images.

Tags:

Gallery