Mô tả sơ về tính năng này là tạo 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.
Code mình share bạn vui lòng đọc kỹ nhé 🙂 Đọc qua 1 lần hết đi rồi làm 1 lần nhá!
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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_test_luoi' ); |
THIẾT KẾ WEB 68 – WEB68
EMAIL: info.thietkeweb68@gmail.com
SĐT: 0359373636 – 0902229139
WEBSITE: thietkeweb68.net