woocommerce checkout page editable products and removeable (mine own last code )
Wed Oct 18 2023 06:34:08 GMT+0000 (Coordinated Universal Time)
// Modify quantity input and add remove icon add_filter('woocommerce_checkout_cart_item_quantity', 'bbloomer_checkout_item_quantity_input', 9999, 3); function bbloomer_checkout_item_quantity_input($product_quantity, $cart_item, $cart_item_key) { $product = apply_filters('woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key); $product_id = apply_filters('woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key); if (!$product->is_sold_individually()) { $product_quantity = woocommerce_quantity_input(array( 'input_name' => 'shipping_method_qty_' . $product_id, 'input_value' => $cart_item['quantity'], 'max_value' => $product->get_max_purchase_quantity(), 'min_value' => '0', ), $product, false); // Add remove icon $product_quantity .= '<a href="#" class="remove-product" data-product-key="' . $cart_item_key . '">x</a>'; $product_quantity .= '<input type="hidden" name="product_key_' . $product_id . '" value="' . $cart_item_key . '">'; } return $product_quantity; } // Add JavaScript to handle product removal add_action('wp_footer', 'add_product_removal_script'); function add_product_removal_script() { ?> <script> document.addEventListener('click', function (event) { if (event.target.classList.contains('remove-product')) { event.preventDefault(); const productKey = event.target.getAttribute('data-product-key'); const form = event.target.closest('form'); if (form && productKey) { // Remove the product from the cart via AJAX jQuery.ajax({ type: 'POST', url: wc_checkout_params.ajax_url, data: { action: 'remove_product_from_cart', product_key: productKey }, success: function (response) { // Reload the checkout page to reflect the updated cart window.location.reload(); } }); } } }); </script> <?php } add_action('wp_ajax_remove_product_from_cart', 'remove_product_from_cart'); function remove_product_from_cart() { if (isset($_POST['product_key'])) { $product_key = sanitize_text_field($_POST['product_key']); WC()->cart->remove_cart_item($product_key); echo 'success'; } wp_die(); } // Detect Quantity Change and Recalculate Totals add_action('woocommerce_checkout_update_order_review', 'bbloomer_update_item_quantity_checkout'); function bbloomer_update_item_quantity_checkout($post_data) { parse_str($post_data, $post_data_array); $updated_qty = false; $updated_remove = false; foreach ($post_data_array as $key => $value) { if (substr($key, 0, 20) === 'shipping_method_qty_') { $id = substr($key, 20); WC()->cart->set_quantity($post_data_array['product_key_' . $id], $post_data_array[$key], false); $updated_qty = true; } elseif (substr($key, 0, 15) === 'remove_product_') { $cart_item_key = substr($key, 15); WC()->cart->remove_cart_item($cart_item_key); $updated_remove = true; } } if ($updated_qty || $updated_remove) { WC()->cart->calculate_totals(); } }
Comments