检查当前的 WooCommerce 产品是否有图像库来运行 jQuery 脚本

问题描述

出于某种原因,除非我检查并运行调试,否则我使用的代码似乎无法加载。也许其他人可以审查并确定?

虽然第一次检查确保它是一个产品页面,但我想要第二次检查以确保产品有一个画廊,如果没有 - 返回。

这是代码

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
}

解决方法

对于您的加载问题,不要使用 jQuery ready 事件,因为它发生在 load 事件之后,因此 load 事件永远不会在您的代码。

您可以使用 WC_Product 方法 get_gallery_image_ids() 如下:

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;
}