Woocommerce使用Ajax类将价格添加到购物车按钮


woocommerce add price to cart button with ajax class

在研究了这个问题之后,我发现了将价格添加到"添加到购物车"按钮的代码,如下所示:

[ $50 加入购物车 ]

由于某种原因,代码不使用 ajax 类,因此单击按钮时页面会重新加载。普通的默认按钮将使用 ajax 类,因此当单击它时,它不会重新加载页面,但会显示一条消息,表明它已添加到购物车中。

我正在覆盖文件添加到购物车.php将其添加到我的主题中''woocommerce''loop''添加到购物车.php

下面是不使用 ajax 类的代码:

echo apply_filters( 'woocommerce_loop_add_to_cart_link',
    sprintf( '<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="button product_type_simple add_to_cart_button ajax_add_to_cart">%s %s</a>',
        esc_url( $product->add_to_cart_url() ),
        esc_attr( $product->id ),
        esc_attr( $product->get_sku() ),
        $product->is_purchasable() ? 'add_to_cart_button' : '',
        esc_attr( $product->product_type ),
        $product->get_price_html(),
        esc_attr( isset( $class ) ? $class : 'button' ),
        esc_html( $product->add_to_cart_text() )
    ),
$product );

如何修改它以使用默认添加到购物车按钮的 ajax 类?

提前致谢

根据我的经验,添加到购物车模板是一个非常危险的模板。你没有说你使用的是哪个版本的WooCommerce,但我假设是2.5?我认为是因为我帮助重写了 WooCommerce ajax 添加到购物车代码以在 .ajax_add_to_cart 类上触发,因为它解决了我在命名您的价格和订阅扩展时遇到的一个复杂问题。但是由于您正在覆盖模板,因此您不会获得 2.5 更新。

下面是新的add-to-cart.php模板和更新的woocommerce_template_add_to_cart()函数。

您可以在第一个中看到传递给模板的类,并在第二个中通过数组上的implode()定义类。因此,要将这段代码导入到您的代码中,您将获得:

echo apply_filters( 'woocommerce_loop_add_to_cart_link',
    sprintf( '<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="button product_type_simple add_to_cart_button ajax_add_to_cart">%s %s</a>',
        esc_url( $product->add_to_cart_url() ),
        esc_attr( $product->id ),
        esc_attr( $product->get_sku() ),
        implode( ' ', array_filter( array(
                        'button',
                        'product_type_' . $product->product_type,
                        $product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
                        $product->supports( 'ajax_add_to_cart' ) ? 'ajax_add_to_cart' : ''
                ) ) ),
        esc_attr( $product->product_type ),
        $product->get_price_html(),
        esc_attr( isset( $class ) ? $class : 'button' ),
        esc_html( $product->add_to_cart_text() )
    ),
$product );

不过,我强烈建议您不要覆盖此模板。从您的代码中,我没有看到任何使其与众不同/自定义的修改,这基本上意味着您在升级时会遇到问题并且没有任何好处。

Button 已经有ajax_add_to_cart绑定 Ajax 调用的类。只需确保您已启用Ajax添加到购物车按钮

转到Woocommerce > Settings > Products > Display并选中Enable AJAX add to cart buttons on archives

此外,它仅在您从产品存档页面添加产品时才有效,在产品单页中不起作用。

参考:配置Woocommerce设置