php - 检查当前 WooCommerce 产品是否有图片库来运行 jQuery 脚本

标签 php jquery woocommerce product image-gallery

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

虽然第一次检查确保它是一个产品页面,但我想要进行二次检查以确保产品有一个图库,如果没有,请返回。

这是代码:

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

关于php - 检查当前 WooCommerce 产品是否有图片库来运行 jQuery 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65538957/

相关文章:

post - PHP 设置? PHP 没有收到 POST 数据

php - 如何在 WooCommerce 中为自定义产品类型启用价格和库存

android - 签名无效 - 提供的签名与来自 Android 的 WooCommerce REST API 调用不匹配

php - 自定义帖子类型中的 WooCommerce 产品

php - 从 PHP 动态排序 HTML 输出

php - 我如何在 Elastic Search 中获得完全匹配的过滤器结果

jquery - 使用 Jquery 从 ajax 调用返回大字符串到 ASP.NET 的 Web 方法

javascript - 有没有可折叠的调整大小菜单插件?

php - 使用php的Mysql事件错误

javascript - jGravity(jQuery 插件)在 Firefox 中无法拖动