Tuesday, March 3, 2020

Custom Thumbnails for Magento 2 Products

I recently migrated a site from Magento 1 to Magento 2.  The product image thumbnails work differently in Magento 2.  In Magento 2 they use a JS library called Fotorama.  It has several options that can be modified in the view.xml if you have a custom theme setup.  However, none of the thumbnail options match the way that the thumbnails work in Magento 1, and my client wanted them to look more like the old version.

I ended up overriding the view⁩/frontend/⁨templates/⁨product/⁨view/gallery.phtml file from the magento/module-catalog module.  In that file I was able to add some custom code that outputs more traditional looking thumbnails. With some simple JS I was able to make clicking on those thumbnails switch the main Fotorama⁩ image.

Below is a quick example of the file.  I have changed it a bit from my production version.  Mostly just cut out some extra code I had in there.  I started with a copy of gallery.phtml from Magento 2.2.4, I believe.  This file has changed somewhat in the latest version, but the basic idea of this technique should still work.  Basically I am getting the images JSON that is used by Fotorama.  Then I convert it back to a php array.  Then I loop over it at the bottom and output divs with the thumbnails and image captions in them.  I also have some css for those that I didn't include here.  Leave a comment if anyone wants to see that.  There is also some JS that adds a click event to the thumbnails that finds the Fotorama slideshow and switches to the correct image.

In my theme I also added an etc/view.xml file.  I copied the contents from vendor/magento/theme-frontend-blank/etc/view.xml and changed the thumbnail setting to just show dots instead of the thumbnails that Fotorama shows by default.  You can also turn the default thumbnails off all together if you want to.

No comments:

Post a Comment


  I'm not sure where I heard this, and it wasn't worded this way, but it helps to think about coding this way. Basically, any progra...