Check if current WooCommerce product has an image Gallery to run a jQuery script

Viewed 790

For some reason, the code I'm using does not seem to load unless I inspect and run a debug. Perhaps someone else can review and make sure?

While the first check makes sure it's a product page, I would like a secondary check making sure the product has a gallery and if not - return.

This is the code:

add_action( 'wp_footer', 'image_swap_on_hover' );
function image_swap_on_hover() {

    if ( ! is_product() ) return;
    // if (???) // check if product has image gallery

    ?>

        <script>

            jQuery( document ).ready( function($) {

                $( window ).load( function() {
        
                    $( '.flexslider' ).flexslider( {
            
                    animation: "slide",
                    controlNav: "thumbnails",
                    start: function() {
                }
            }
        );

        $( ".flex-control-thumbs li img" ).hover( function() {

            $(this).click();
        
            }
        );
            }
        );
            }
        );

    </script>

<?php
}
1 Answers

For your loading problem, don't use jQuery ready event as it comes after load event, so the load event never get triggered in your code.

You can use the WC_Product method get_gallery_image_ids() as follows:

add_action( 'wp_footer', 'image_swap_on_hover' );
function image_swap_on_hover() {
    if ( ! is_product() ) 
        return;

    global $product;

    if ( ! is_a( $product, 'WC_Product' ) ) {
        $product = wc_get_product( get_the_id() );
    }

    // Get product gallery image ids
    $gallery_image_ids = $product->get_gallery_image_ids();
    
    // Check if product gallery image ids is not empty
    if ( ! empty($gallery_image_ids) ) :
    ?>
    <script>
    jQuery( function($) {
        $( window ).load( function() {
            console.log( 'window LOAD event' ); // Only for testing (to be removed)

            $( '.flexslider' ).flexslider( {
                animation: "slide",
                controlNav: "thumbnails",
                start: function() {
                    // do something
                }
            });
    
            $( ".flex-control-thumbs li img" ).hover( function() {
                $(this).click();
            });
        });
    });
    </script>
    <?php
    endif;
}
Related