Sometimes clients ask me how can to add the thumbnails to the product loop, today I share my solution.
Keep in mind that this will be diferent theme to theme so you may need to adjust some code in here, you will require some PHP/JS/CSS kownlede.
- Let’s start by adding to your theme functions.php (always use a child theme).
add_action('woocommerce_after_shop_loop_item', 'svi_product_tn_images'); function svi_product_tn_images() { global $product; if ($product) { #IMAGE THUMNAILS $attachment_ids = !empty($product->get_gallery_image_ids()) ? $product->get_gallery_image_ids() : ''; $post_thumbnail_id = get_post_thumbnail_id($product->get_id()); $post_thumbnail = wp_get_attachment_image_src($post_thumbnail_id, 'thumbnail'); $count = 1; if ($attachment_ids != '') { foreach ($attachment_ids as $a_id) { if ($count == 1 || $count > 4) { if ($count == 1) { echo ' <div class="tn_wrapper">'; echo wp_get_attachment_image(get_post_thumbnail_id($product->get_id()), 'shop_catalog', false, array("class" => "tn_img tn_current_img attachment-svi-icon size-svi-icon")); } else { echo ' </div>'; echo ' <div class="tn_wrapper">'; } $count = 1; } echo wp_get_attachment_image($a_id, 'shop_catalog', false, array("class" => "tn_img . attachment-svi-icon size-svi-icon")); $count++; } echo ' </div>'; } } }
- Add some styling, this will need some costumization to fit your needs.
.tn_img { border: solid 1px lightgray !important; width: 35px !important; height: 31px !important; display: inline-block !important; margin: 1px !important; cursor: pointer; -webkit-transition: 250ms; -moz-transition: 250ms; -o-transition: 250ms; transition: 250ms; } .tn_current_img { border: solid 1px #ff5a00 !important; opacity: 0.3; } .wp-post-image { -webkit-transition: 100ms; -moz-transition: 100ms; -o-transition: 100ms; transition: 100ms; } .tn_wrapper:first-of-type { margin-top: 5px; }
- Add some JS to your theme JavaScript file or footer.php with the <script> tags:
jQuery('.tn_img').click(function (e) { if (!jQuery(this).hasClass('tn_current_img')) { jQuery(this).siblings().removeClass('tn_current_img'); jQuery(this).parent().siblings('.tn_wrapper').children('.tn_img').removeClass('tn_current_img'); product_img = jQuery(this).closest('.product').find('a.woocommerce-LoopProduct-link').children('img'); // You may need to adjust this tn_img_src = jQuery(this).attr('src'); tn_img_srcset = jQuery(this).attr('srcset'); tn_img_alt = jQuery(this).attr('alt'); tn_img_woovsi = jQuery(this).data('woovsi'); product_img.css('opacity', 0); setTimeout(function () { product_img.attr('src', tn_img_src); product_img.attr('srcset', tn_img_srcset); product_img.css('opacity', 1); }, 100); jQuery(this).addClass('tn_current_img'); } });
I hope this helps out!
Cheers,
David