woocommerce product custom gallery slider example

Sumit Singh
Sumit Singh
10 Mar 2023

Here is an example code snippet for creating a custom gallery slider for WooCommerce products:

add_action( 'woocommerce_product_thumbnails', 'custom_product_gallery_slider', 20 );
function custom_product_gallery_slider() {
    global $product;

    $attachment_ids = $product->get_gallery_image_ids();
    if ( $attachment_ids ) {
        echo '<div id="product-gallery-slider" class="product-gallery-slider owl-carousel owl-theme">';
        foreach ( $attachment_ids as $attachment_id ) {
            echo '<div class="item"><a href="' . esc_url( wp_get_attachment_url( $attachment_id ) ) . '">' . wp_get_attachment_image( $attachment_id, 'woocommerce_thumbnail' ) . '</a></div>';
        }
        echo '</div>';
    }
}

add_action( 'wp_enqueue_scripts', 'custom_product_gallery_slider_scripts' );
function custom_product_gallery_slider_scripts() {
    wp_enqueue_style( 'owl-carousel', 'https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css' );
    wp_enqueue_style( 'owl-theme', 'https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.theme.default.min.css' );
    wp_enqueue_script( 'owl-carousel', 'https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js', array( 'jquery' ), '2.3.4', true );
    wp_enqueue_script( 'custom-product-gallery-slider', get_stylesheet_directory_uri() . '/js/custom-product-gallery-slider.js', array( 'jquery', 'owl-carousel' ), '1.0', true );
}

// custom-product-gallery-slider.js
jQuery(document).ready(function($) {
    $('#product-gallery-slider').owlCarousel({
        loop: true,
        margin: 10,
        nav: true,
        dots: false,
        autoplay: true,
        autoplayTimeout: 5000,
        autoplayHoverPause: true,
        responsive: {
            0: {
                items: 1
            },
            600: {
                items: 2
            },
            1000: {
                items: 3
            }
        }
    });
});

In this example, we are using the woocommerce_product_thumbnails action hook to add a custom gallery slider to the product page. We are using the Owl Carousel jQuery plugin to create the slider and enqueueing its required CSS and JS files. We are also enqueuing a custom JS file custom-product-gallery-slider.js where we initialize the slider with custom options.

Note: This code assumes that you have already added support for the WooCommerce gallery on your child themeโ€™s functions.php file or via a plugin that allows custom functions to be added, such as the Code snippets plugin.

Was this article helpful?

Tags

Categories

Never miss new post again

Subscribe and get list of new posts in your inbox

Click to Copy