简体   繁体   English

将数量字段添加到 WooCommerce 商店页面上的 Ajax 添加到购物车按钮

[英]Add a quantity field to Ajax add to cart button on WooCommerce shop page

I am new to Woocommerce.我是 Woocommerce 的新手。 I was trying to show the quantity box in the shop page.我试图在商店页面中显示数量框。 I have used the below code and it's working as expected:我使用了下面的代码,它按预期工作:

add_action( 'woocommerce_before_shop_loop', 'handsome_bearded_guy_select_variations' );

function handsome_bearded_guy_select_variations() {
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_single_add_to_cart', 30 );
}

But the problem is that ajax add to cart button got replaced with default one.但问题是 ajax 添加到购物车按钮被默认按钮替换了。

How can I enable back the ajax functionality on add to cart button with quantity field for Woocommerce archives pages?如何在 Woocommerce 档案页面的带有数量字段的添加到购物车按钮上启用 ajax 功能?

Updated on 2021 2021 年更新

For WooCommerce versions from 3.2 to 5+, Optimized jQuery code and Removed a quantity bug.对于从 3.2 到 5+ 的 WooCommerce 版本,优化了 jQuery 代码并删除了数量错误。 Added quantity reset after add to cart.添加到购物车后添加数量重置。


The following custom function is hooked in woocommerce_loop_add_to_cart_link filter hook and adds a quantity input field to each product on WooCommerce archives pages and other product loops.以下自定义函数挂钩在woocommerce_loop_add_to_cart_link过滤器挂钩中,并为 WooCommerce 存档页面和其他产品循环上的每个产品添加数量输入字段。 We use here mostly the original WooCommerce code.我们在这里主要使用原始的 WooCommerce 代码。

A bit of jQuery code is necessary to update the data-quantity attribute on the add to cart button when customer changes the quantity.当客户更改数量时,需要一些 jQuery 代码来更新添加到购物车按钮上的data-quantity属性。 Some styling might be needed, depending on your client wishes (and on your theme) .可能需要一些样式,这取决于您的客户希望(和您的主题)

An additional section to hide the "View cart" button is located at the end.隐藏“查看购物车”按钮的附加部分位于末尾。

The code:代码:

add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_loop_ajax_add_to_cart', 10, 2 );
function quantity_inputs_for_loop_ajax_add_to_cart( $html, $product ) {
    if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
        // Get the necessary classes
        $class = implode( ' ', array_filter( array(
            'button',
            'product_type_' . $product->get_type(),
            $product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
            $product->supports( 'ajax_add_to_cart' ) ? 'ajax_add_to_cart' : '',
        ) ) );

        // Embedding the quantity field to Ajax add to cart button
        $html = sprintf( '%s<a rel="nofollow" href="%s" data-quantity="%s" data-product_id="%s" data-product_sku="%s" class="%s">%s</a>',
            woocommerce_quantity_input( array(), $product, false ),
            esc_url( $product->add_to_cart_url() ),
            esc_attr( isset( $quantity ) ? $quantity : 1 ),
            esc_attr( $product->get_id() ),
            esc_attr( $product->get_sku() ),
            esc_attr( isset( $class ) ? $class : 'button' ),
            esc_html( $product->add_to_cart_text() )
        );
    }
    return $html;
}

add_action( 'wp_footer' , 'archives_quantity_fields_script' );
function archives_quantity_fields_script(){
    ?>
    <script type='text/javascript'>
        jQuery(function($){
            // Update data-quantity
            $(document.body).on('click input', 'input.qty', function() {
                $(this).parent().parent().find('a.ajax_add_to_cart').attr('data-quantity', $(this).val());
                $(".added_to_cart").remove(); // Optional: Removing other previous "view cart" buttons
            }).on('click', '.add_to_cart_button', function(){
                var button = $(this);
                setTimeout(function(){
                    button.parent().find('.quantity > input.qty').val(1); // reset quantity to 1
                }, 1000); // After 1 second

            });
        });
    </script>
    <?php
}

Code goes in functions.php file of your active child theme (active theme).代码位于您的活动子主题(活动主题)的 functions.php 文件中。
Tested and works on WooCommerce version 4.1.1 and WordPress 4.5.1 on Storefront theme.在店面主题的 WooCommerce 版本 4.1.1 和 WordPress 4.5.1 上测试并运行。


Hiding "View cart" button (when using Ajax add to cart) :隐藏“查看购物车”按钮(使用 Ajax 添加到购物车时)

1). 1)。 You can add this CSS rule to the styles.css file located in your active theme:您可以将此 CSS 规则添加到活动主题中的 styles.css 文件中:

a.added_to_cart.wc-forward {
    display:none;
}

2). 2)。 You can use the following hoocked function (first option is the best way) :您可以使用以下挂钩函数(第一个选项是最好的方法)

add_action( 'wp_head' , 'hide_ajax_view_cart_button' );
function hide_ajax_view_cart_button(){
    if( is_shop() || is_product_category() || is_product_tag() ): ?>
    <style>
        a.added_to_cart.wc-forward {
            display:none;
        }
    </style>
    <?php endif;
}

Code goes in function.php file of your active child theme (active theme).代码位于活动子主题(活动主题)的 function.php 文件中。

Does everything as above, without the "quantity bug".执行上述所有操作,没有“数量错误”。

The code:代码:

add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_loop_ajax_add_to_cart', 10, 2 );
function quantity_inputs_for_loop_ajax_add_to_cart( $html, $product ) {
    if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
        // Get the necessary classes
        $class = implode( ' ', array_filter( array(
            'button',
            'product_type_' . $product->get_type(),
            $product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
            $product->supports( 'ajax_add_to_cart' ) ? 'ajax_add_to_cart' : '',
        ) ) );

        // Adding embeding <form> tag and the quantity field
        $html = sprintf( '%s%s<a rel="nofollow" href="%s" data-quantity="%s" data-product_id="%s" data-product_sku="%s" class="%s">%s</a>%s',
        '<form class="cart">',
        woocommerce_quantity_input( array(), $product, false ),
        esc_url( $product->add_to_cart_url() ),
        esc_attr( isset( $quantity ) ? $quantity : 1 ),
        esc_attr( $product->get_id() ),
        esc_attr( $product->get_sku() ),
        esc_attr( isset( $class ) ? $class : 'button' ),
        esc_html( $product->add_to_cart_text() ),
        '</form>'
        );
    }
    return $html;
}

add_action( 'wp_footer' , 'archives_quantity_fields_script' );
function archives_quantity_fields_script(){
    //if( is_shop() || is_product_category() || is_product_tag() ): ?>
    <script type='text/javascript'>
        jQuery(function($){
            // Update quantity on 'a.button' in 'data-quantity' attribute (for ajax)
            $(".add_to_cart_button.product_type_simple").on('click', function() { var $button = $(this); $button.data('quantity', $button.parent().find('input.qty').val()); });        
            // remove old "view cart" text, only need latest one thanks!
            $(document.body).on("adding_to_cart", function() {
                $("a.added_to_cart").remove();
            });
        });
    </script>
    <?php //endif;
}

References:参考资料:

@LoicTheAztec's entry above 11 Feb 2018. @LoicTheAztec 于 2018 年 2 月 11 日以上的条目。

@braciawrite's and @andrewmclagan's GitHub entries on 11 Dec 2015 and 15 Mar 2018 respectively. @braciawrite 和 @andrewmclagan 的 GitHub 条目分别于 2015 年 12 月 11 日和 2018 年 3 月 15 日。

https://gist.github.com/webaware/6260326 https://gist.github.com/webaware/6260326

Note:注意:

Code should perform the check when "add_to_cart" button is pressed, not on quantity change.代码应该在按下“add_to_cart”按钮时执行检查,而不是数量变化。

I've commented out the if and endif statements under function "archives_quantity_fields_script" as I am running this code on a custom page with WooCommerce products.我在带有 WooCommerce 产品的自定义页面上运行此代码时,已注释掉函数“archives_quantity_fields_script”下的 if 和 endif 语句。

Hope this helps!希望这有帮助!

Here is an alternative method which seems to work well in Woo 3+这是一种在 Woo 3+ 中似乎运行良好的替代方法

<?php
/**
 * Add quantity field on the archive page.
 */
function custom_quantity_field_archive() {

    $product = wc_get_product( get_the_ID() );

    if ( ! $product->is_sold_individually() && 'variable' != $product->get_type() && $product->is_purchasable() ) {
    woocommerce_quantity_input( array( 'min_value' => 1, 'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity() ) );
    }

}
add_action( 'woocommerce_after_shop_loop_item', 'custom_quantity_field_archive', 0, 9 );

/**
 * Enqueue the JavaScript.
 */
function custom_add_to_cart_quantity_handler() {

wc_enqueue_js( '
    jQuery( ".post-type-archive-product" ).on( "click", ".quantity input", function() {
        return false;
    });
    jQuery( ".post-type-archive-product" ).on( "change input", ".quantity .qty", function() {
        var add_to_cart_button = jQuery( this ).parents( ".product" ).find( ".add_to_cart_button" );
        
        // For AJAX add-to-cart actions
        add_to_cart_button.attr( "data-quantity", jQuery( this ).val() );

        // For non-AJAX add-to-cart actions
        add_to_cart_button.attr( "href", "?add-to-cart=" +   add_to_cart_button.attr( "data-product_id" ) + "&quantity=" + jQuery( this ).val() );
    });
' );

}
add_action( 'init', 'custom_add_to_cart_quantity_handler' );

There may be several options for the jQuery, depending on what Ajax actions are on your page. jQuery 可能有多个选项,具体取决于页面上的 Ajax 操作。

It took me a whole day to get this working - but here is the code that worked for me.我花了一整天才完成这项工作 - 但这是对我有用的代码。 Add to your functions.php - its adapted from the above and I'm on WooCommerce 5.0.0添加到您的functions.php - 它改编自上述内容,我在 WooCommerce 5.0.0

add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_loop_ajax_add_to_cart', 10, 2 );
function quantity_inputs_for_loop_ajax_add_to_cart( $html, $product ) {
    if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
        // Get the necessary classes
        $class = implode( ' ', array_filter( array(
            'button',
            'product_type_' . $product->get_type(),
            $product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
            $product->supports( 'ajax_add_to_cart' ) ? 'ajax_add_to_cart' : '',
        ) ) );

        // Adding embeding <form> tag and the quantity field
        $html = sprintf( '%s%s<a rel="nofollow" href="%s" data-quantity="%s" data-product_id="%s" data-product_sku="%s" class="%s">%s</a>%s',
        '<form class="cart">',
        woocommerce_quantity_input( array(), $product, false ),
        esc_url( $product->add_to_cart_url() ),
        esc_attr( isset( $quantity ) ? $quantity : 1 ),
        esc_attr( $product->get_id() ),
        esc_attr( $product->get_sku() ),
        esc_attr( isset( $class ) ? $class : 'button' ),
        esc_html( $product->add_to_cart_text() ),
        '</form>'
        );
    }
    return $html;
}

add_action( 'wp_footer' , 'archives_quantity_fields_script' );

function archives_quantity_fields_script(){
    //if( is_shop() || is_product_category() || is_product_tag() ): ?>
    <script type='text/javascript'>
        jQuery( document ).ready( function( $ ) {
        $( document ).on( 'change', '.quantity .qty', function() {
            $( this ).parent( '.quantity' ).next( '.add_to_cart_button' ).attr( 'data-quantity', $( this ).val() );
            //alert("Changed");
        });
    });
        
        jQuery(function($) {
            // Update quantity on 'a.button' in 'data-quantity' attribute (for ajax) 
            $(".add_to_cart_button.product_type_simple").on('click', function() {
                var $button = $(this);
                $button.data('quantity', $button.parent().find('input.qty').val());
            });
            // remove old "view cart" text, only need latest one thanks!
            $(document.body).on("adding_to_cart", function() {
                $("a.added_to_cart").remove();
            });
        });
    </script>
    <?php //endif;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 添加数量单选字段到 Ajax 添加到 WooCommerce 商店页面上的购物车按钮 - Add a quantity radio selector field to Ajax add to cart button on WooCommerce shop page WooCommerce商店页面:添加到购物车按钮上的数量输入 - WooCommerce Shop page: Quantity input on add to cart button WooCommerce添加数量按钮到商店 - WooCommerce add quantity button to shop 在 WooCommerce 商店页面上添加数量字段并添加到购物车按钮 - Adding quantity fields and add to cart buton on WooCommerce Shop page 在 Woocommerce 3 商店页面上的添加到购物车下添加额外按钮 - Add Extra button under Add to cart on shop page of Woocommerce 3 Woocommerce商店页面(类别页面模板)添加到购物车按钮行为 - Woocommerce shop page (category page template) Add to cart button behavior 在结帐时添加一个按钮以清空购物车并重定向到Woocommerce中的商店页面 - Add a button in checkout to empty cart and redirect to shop page in Woocommerce 在Woocommerce商店页面中更改用于简单产品的购物车按钮 - Change add-to-cart button for simple products in Woocommerce shop page 更改商店页面中 woocommerce 商店中“添加到购物车”按钮的重定向 - Changing the redirect of the “add to cart” button in woocommerce store in Shop page 在 Woocommerce 商店页面上自定义添加到购物车按钮 - Customizing add to cart buttons on Woocommerce shop page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM