Skip to main content

[Thủ thuật WP] Hướng dẫn thêm trường số lượng và nút thêm vào giỏ ra trang shop – woocommerce

Tính năng này là một shortcode tạo trường số lượng và button thêm vào giỏ bằng ajax (add to cart ajax)  hiển thị trên trang shop - woocommerce.

Bước 1 - Tạo button Add to cart và trường số lượng

Mở file functions.php trong theme và thêm đoạn code 

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);

Chúng ta sử dụng hook woocommerce_after_shop_loop_item để hiển thị html của button và trường số lượng.  Bạn có thể sử dụng hook khác để hiển thị vị trí theo mong muốn của mình.

Bước 2 - Thêm Style để cho đẹp hơn

Mở file styles.css trong theme ( có thể khác tùy theme) và thêm đoạn code 

  .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;
        }

Bước 3 - Thêm code Javascript để xử lý trường số lượng

Tìm file custom.js trong theme( có thể là khác tùy mỗi theme) và thêm đoạn code dưới vào 

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());
});