简体   繁体   中英

add quantity select to woocommerce shopping cart widget

i like to give the clients an option to add more product in the woocommerce shopping cart widget.

so far i managed to find this code:

add_filter( 'woocommerce_widget_cart_item_quantity', 'add_minicart_quantity_fields', 10, 3 );
function add_minicart_quantity_fields( $html, $cart_item, $cart_item_key ) {
    $product_price = apply_filters( 'woocommerce_cart_item_price', WC()->cart->get_product_price( $cart_item['data'] ), $cart_item, $cart_item_key );

    return woocommerce_quantity_input( array('input_value' => $cart_item['quantity']), $cart_item['data'], false ) . $product_price;
}

the code make the quantity select visible in the shopping cart. but the issue is when we change the quantity, no changes take place... If i understand correctly i should add a Ajax request to change the product's quantity when the user add or remove products.

anyone has a solution?

to display select quantity in minicarts

I also wanted to add quantity buttons to the Woocommerce shopping cart widget . I achieved this by combining your code with a modified version of this answer: https://stackoverflow.com/a/69218525/4234891

We will send the quantity via AJAX, update the quantity in the backend, and send the cart subtotal back.

So first create the quanity buttons like you already did. In functions.php add:

add_filter('woocommerce_widget_cart_item_quantity', 'add_minicart_quantity_fields', 10, 3);
function add_minicart_quantity_fields($html, $cart_item, $cart_item_key)
{
    $product_price = apply_filters('woocommerce_cart_item_price', WC()->cart->get_product_price($cart_item['data']), $cart_item, $cart_item_key);

    return woocommerce_quantity_input(array('input_value' => $cart_item['quantity']), $cart_item['data'], false) . $product_price;
}

Next, register the JavaSript. In functions.php add :

add_action('wp_enqueue_scripts', function () {
    wp_register_script('custom-cart-widget', get_stylesheet_directory_uri() . '/js/cart-widget.js', ['jquery'], '1.0', true);
    wp_localize_script('custom-cart-widget', 'cart_widget_qty_ajax', ['ajax_url' => admin_url('admin-ajax.php')]);
    wp_enqueue_script('custom-cart-widget');
});

Next, add the function which will be called via AJAX. In functions.php add :

function ajax_change_widget_cart_qty()
{
    // Set item key as the hash found in input.qty's name
    $cart_item_key = $_POST['hash'];

    // Get the array of values owned by the product we're updating
    $cart_item_values = WC()->cart->get_cart_item($cart_item_key);

    // Get the quantity of the item in the cart
    $product_quantity = apply_filters('woocommerce_stock_amount_cart_item', apply_filters('woocommerce_stock_amount', preg_replace("/[^0-9\.]/", '', filter_var($_POST['quantity'], FILTER_SANITIZE_NUMBER_INT))), $cart_item_key);

    // Update cart validation
    $passed_validation = apply_filters('woocommerce_update_cart_validation', true, $cart_item_key, $cart_item_values, $product_quantity);

    // Update the quantity of the item in the cart
    if ($passed_validation) {
        WC()->cart->set_quantity($cart_item_key, $product_quantity, true);
    }

    wp_send_json_success(['subtotal_html' => WC()->cart->get_cart_subtotal()]);
}

add_action('wp_ajax_change_widget_cart_qty', 'ajax_change_widget_cart_qty');
add_action('wp_ajax_nopriv_change_widget_cart_qty', 'ajax_change_widget_cart_qty');

Last, create a file in your_theme/js/cart-widget.js and add :

jQuery(document).ready(function($) {
    jQuery(document).on('change', '.woocommerce.widget_shopping_cart input.qty', function(){
        var value = $(this).val();
        if (!isNaN(value) && value > 0) {
            var holder = $(this).closest('li');
            if (holder.length) {
                var removeButton = $(holder).find('.remove_from_cart_button');
                if (removeButton.length) {
                    var itemHash = removeButton.attr('data-cart_item_key');
                    if (itemHash) {

                        holder.block({
                            message: null,
                            overlayCSS: {
                                opacity: 0.6
                            }
                        });

                        $.ajax({
                            type: 'POST',
                            dataType: 'json',
                            url: cart_widget_qty_ajax.ajax_url,
                            data: {
                                action: 'change_widget_cart_qty',
                                hash: itemHash,
                                quantity: value,
                            },
                            success: function(response) {
                                if (response.data.subtotal_html) {
                                    var miniCart = $(holder).closest('div.widget_shopping_cart_content');
                                    if (miniCart.length) {
                                        var subTotalHolder = $(miniCart).find('.woocommerce-mini-cart__total .woocommerce-Price-amount.amount');
                                        if (subTotalHolder) {
                                            subTotalHolder.replaceWith(response.data.subtotal_html);
                                        }
                                    }
                                }
                            },
                            complete: function() {
                                holder.css( 'opacity', '1' ).unblock();
                            },
                        });
                    }
                }

            }
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM