Nội dung bài viết
Thêm trường số lượng ra trang shop woocommerce
Đây là một tính năng được tạo để thêm trường số lượng ngay trên trang shop, hay các shortcode liên quan đến woocommerce.
Kèm theo đó là nút add to cart ajax. Để khách có thể dễ dàng thêm vào giỏ sản phẩm và số lượng tùy chỉnh mà không cần phải vào trang chi tiết sản phẩm.
Bắt đầu thôi.!
Tạo cấu trúc html gồm chọn số lượng và nút add to cart
<?php // Nhớ xóa <?php khi cho vào function.php function isures_custom_quantity_field_archive() { global $product; if ($product->is_type('simple')) { echo '<div class="isures-custom--qty_wrap">'; echo '<div class="isures-qtv--wrap">'; woocommerce_quantity_input(array('min_value' => 1, 'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity())); echo '</div>'; woocommerce_template_loop_add_to_cart(); echo '</div>'; } } add_action('woocommerce_after_shop_loop_item', 'isures_custom_quantity_field_archive', 15, 9);
Mình hook vào woocommerce_after_shop_loop_item . Nếu bạn muốn thay đổi vị trí khác có thể tham khảo các hook archive shop khác thay thế woocommerce_after_shop_loop_item ở code trên.
Làm đẹp code tạo field số lượng và nút add to cart với vài dòng css
add_action('wp_footer', 'isures_quantity_reg_style'); function isures_quantity_reg_style() { ?> <style> .isures-custom--qty_wrap { display: flex; align-items: center; justify-content: space-between; } .isures-custom--qty_wrap .ajax_add_to_cart { font-size: 12px; margin: 0; padding: 10px 15px; min-height: auto; line-height: 1.5; } </style> <?php }
Js xử lý field số lượng khi thay đổi.
function isures_custom_add_to_cart_quantity_handler() { wc_enqueue_js(' jQuery( "body" ).on( "click", ".quantity input", function() { return false; }); jQuery( "body" ).on( "change input", ".quantity .qty", function() { var add_to_cart_button = jQuery( this ).parents( ".product" ).find( ".add_to_cart_button" ); add_to_cart_button.attr( "data-quantity", jQuery( this ).val() ); add_to_cart_button.attr( "href", "?add-to-cart=" + add_to_cart_button.attr( "data-product_id" ) + "&quantity=" + jQuery( this ).val() ); }); '); } add_action('init', 'isures_custom_add_to_cart_quantity_handler');
Ok, vậy là xong rồi đấy. Chúc bạn thành công.