首页 > 解决方案 > 如何在我的 functions.php 中做一个 IF 语句来确定我是否在单打产品页面上?(woocommerce)

问题描述

您好已经制作了一个 php 函数,可以将脚本上传到带有“购物车”的页面is_cart(),这一切似乎都正常工作。但是当我尝试使用is_product()它时,它并没有在单个产品页面上注册。如何让我的 php 在单个产品页面上呈现脚本?

我在我的functions.php中调用这个函数

function refresh_update_qty() {
    if (is_cart() || is_product()):
        ?>
        <script type="text/javascript">

            jQuery('div.woocommerce').on('click', ' button.plus, button.minus', function(e){
                var math_method = '';
                if(jQuery(this).hasClass('plus')) {
                    math_method = "1";
                }else if(jQuery(this).hasClass('plus')) {
                    math_method = "-1";
                } else {
                //    Do nothing
                }
                var this_input = this.parentNode.querySelector('input[type=number]');
                var current_val = this_input.value;
                var new_val = parseInt(current_val) + parseInt(math_method);
                this_input.value = new_val;
                document.getElementById('update_cart_button').disabled = false;
                <?php
                if(is_cart()):
                ?>
                jQuery("[name='update_cart']").trigger("click");
                <?php
                endif;
                ?>
                e.preventDefault();
            });

        </script>
        <?php
    endif;
}
add_action( 'wp_footer', 'refresh_update_qty' );

根据 woocommerce 文档, is_product() 应该可以工作,但不能。https://woocommerce.wp-a2z.org/oik_api/is_product/

标签: javascriptphpwordpresswoocommerce

解决方案


我解决了这个问题。好像我的产品页面在正文中有 woocommerce 类,而我的购物车在 div 中有它。所以一旦我改变它就可以了jQuery('div.woocommerce')jQuery('.woocommerce')

最终代码如下

function refresh_update_qty() {
    if (is_cart() || is_product()):
        ?>
        <script type="text/javascript">
            (function($) {

            $('.woocommerce').on('click', ' button.plus, button.minus', function(e){
                var math_method = '';
                if($(this).hasClass('plus')) {
                    math_method = "1";
                }else if($(this).hasClass('minus')) {
                    math_method = "-1";
                } else {
                //    Do nothing
                }
                var this_input = this.parentNode.querySelector('input[type=number]');
                var current_val = this_input.value;
                var new_val = parseInt(current_val) + parseInt(math_method);
                this_input.value = new_val;
                <?php
                if(is_cart()):
                ?>
//                IF CART PAGE UPDATE CART
                document.getElementById('update_cart_button').disabled = false;
                $("[name='update_cart']").trigger("click");
                <?php
                endif;
                ?>
                e.preventDefault();
            });
            })( jQuery );

        </script>
        <?php
    endif;
}
add_action( 'wp_footer', 'refresh_update_qty' );

推荐阅读