WooCommerce: How to Reuse Zoom/Lightbox Scripts On Non-Product Images

WooCommerce product images on the Single Product page get the default Zoom + Lightbox + Photoswipe behavior. This is super helpful when the images are super important for sales conversion, and less helpful in other cases (in fact, here’s a snippet to disable Zoom etc. from the Woo product pages).

Now, the challenge that I had on this same website was that I wanted blog readers to also enjoy the same WooCommerce zoom / lightbox features on blog post images and screenshots. So, without reinventing the wheel, I’m now loading the WooCommerce scripts on pages like this one (single post), and on image click I trigger the lightbox!

You can test the feature by clicking on the image below. Enjoy!

Try clicking on this image!

PHP Snippet: Use the WooCommerce Zoom/Lightbox Scripts On Blog Post Images

If a single post is being viewed and the current theme supports the WooCommerce product gallery lightbox, the snippet below adds the necessary scripts and styles to enable the WooCommerce lightbox effect.

Additionally, it enhances the image interaction by adding a click listener for images in the post content. When an image is clicked, it creates a photoswipe gallery, allowing users to view the image in a larger size with options for navigation.

The only thing that you need to change in the script is the image selector. I use .entry-content > .wp-block-image .aligncenter because I want to apply this lightbox script only to images that are in the post body, that are embedded via the block image, and that are center aligned.

So, unless you define the proper selector, this won’t work on your site. Be as specific as possible, otherwise this will trigger on all images including the footer, header, sidebar, etc.

/**
 * @snippet       Enable Woo Lightbox for post images
 * @tutorial      Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 8
 * @community     Join https://businessbloomer.com/club/
 */

// ------------------
// 1. Load scripts on single post

add_action( 'wp_enqueue_scripts', 'bbloomer_load_woo_photoswipe_also_on_posts' );

function bbloomer_load_woo_photoswipe_also_on_posts() {
	if ( is_single() ) {
		if ( current_theme_supports( 'wc-product-gallery-lightbox' ) ) {
			wp_enqueue_script( 'photoswipe-ui-default' );
			wp_enqueue_style( 'photoswipe-default-skin' );
			add_action( 'wp_footer', 'woocommerce_photoswipe' );
		}
	}
}

// ------------------
// 2. Trigger lightbox on images

add_action( 'wp_footer', 'bbloomer_photoswipe_click_listener' );

function bbloomer_photoswipe_click_listener() {
   if ( ! is_single() ) return;
	wc_enqueue_js( "
		$('.entry-content > .wp-block-image .aligncenter').hover(function() {
			$(this).css('cursor','pointer');
		});
		$('body').on('click','.entry-content > .wp-block-image .aligncenter',function(e){
			var pswpElement = $( '.pswp' )[0],
				items = [],
				clicked = $(this),
				img = clicked.find('img');
			if ( ! img.length ) return false;
			items.push( {
				alt: img.attr( 'alt' ),
				src: img.attr( 'src' ),
				w: img.prop('naturalWidth'),
				h: img.prop('naturalHeight'),
				title: clicked.find('figcaption') ? clicked.find('figcaption').text() : false
			} );
			var options = { 
				index: $( clicked ).index(),
				addCaptionHTMLFn: function( item, captionEl ) {
					if ( ! item.title ) {
						captionEl.children[0].textContent = '';
						return false;
					}
					captionEl.children[0].textContent = item.title;
					return true;
				}
			};
			var photoswipe = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options );
			photoswipe.init();
		});		
	");
}

Where to add custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101

Related content

  • WooCommerce: Add Content Below Single Product Images
    One of the latest WooCommerce versions introduced an optimized product gallery on the single product page. If your products have multiple images and therefore use the product gallery, you might want to also add content below the gallery itself. But… If you’re familiar with WooCommerce customization and WooCommerce hooks (and specifically the ones of the […]
  • WooCommerce: Show Video Instead of Product Images
    This week’s snippet is a very easy – yet helpful – one. Many ecommerce entrepreneurs prefer to display a YouTube video instead of a static, boring, featured image and product gallery. Of course, not all products are created equal. So, let’s see how to make this work for a specific product ID only. Enjoy!
  • Show WooCommerce Product Images @ CheckoutWooCommerce: Show Product Images @ Checkout Page
    The Order Review section of the WooCommerce Checkout Page shows the product name, quantity and subtotal. No sign of the product image, which can be very useful to identify/differentiate between similar products or product variations. This simple snippet will help you display just that: the featured image beside the product name inside the order review […]
  • WooCommerce: How To Change Product Image Sizes
    WooCommerce lets you resize the product images on Single Product and Shop pages from Appearance > Customize > WooCommerce > Product Images. Besides, you donโ€™t have to manually regenerate the images after resizing them with an additional plugin, as WooCommerce can crop, resize and automatically regenerate image sizes out of the box. Despite this seems […]
  • WooCommerce: Switch Image Background On Color Variation Selection
    You could upload 10 images, one for each color of your variable product… or you could be slightly smarter and use 1 image only, and then when the user selects a color trigger a background color change! Easier to code than to explain, so let’s take a look at the screenshot below (image must be […]

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza. Follow @rmelogli

Questions? Feedback? Customization? Leave your comment now!
_____

If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining the Business Bloomer Club to get quick WooCommerce support. Thank you!

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