Bạn muốn tích hợp thêm ô tìm kiếm sản phẩm trên website của mình giống như các sàn thương mại điện tử Shopee, Lazada, Tiki mà không cần sử dụng Plugin? Trong bài viết hôm nay, chúng tôi sẽ hướng dẫn bạn cách thêm ô tìm kiếm sản phẩm dạng Ajax, không cần phải sử dụng plugin giúp tiết kiệm tài nguyên và tùy chỉnh giao diện theo ý muốn.
Ưu điểm của việc thêm ô tìm kiếm sản phẩm bằng mã
Sử dụng code thuần để tạo ô tìm kiếm sản phẩm WordPress bằng code mang lại nhiều lợi ích:
- Tối ưu hiệu suất: Không cần cài thêm plugin, giảm tải cho website.
- Tùy chỉnh linh hoạt: Dễ dàng điều chỉnh giao diện và chức năng theo nhu cầu.
- Kiểm soát tốt hơn: Bạn có toàn quyền quản lý mã nguồn, đảm bảo phù hợp với theme và cấu trúc website.
Trình tự các bước để thêm ô tìm kiếm sản phẩm dạng Ajax
Bước 1: Thêm CSS Cho Giao Diện Ô Tìm Kiếm
Để tạo giao diện đẹp và thân thiện cho ô tìm kiếm, bạn cần thêm đoạn CSS sau vào file style.css của theme hoặc trong phần Customizer > Additional CSS:
/* Search Ajax Header */
#custom_search_form {
display: flex;
flex-direction: row;
font-size: 14px;
line-height: 1.5;
position: relative;
}
#custom_search_form .form-group.input-search {
width: 100%;
}
#custom_search_form .form-group.input-search input {
border: 1px solid #f5f5f5;
width: 100%;
font-size: 14px;
color: #333333;
line-height: 1.5;
font-weight: 400;
height: 42px;
background-color: #f5f5f5;
border-radius: 4px;
padding: 5px 20px 5px 45px;
}
#custom_search_form .form-group.input-search:before {
content: "\f375";
font-family: Ionicons;
font-style: normal;
font-weight: 400;
line-height: 1;
font-size: 22px;
position: absolute;
left: 20px;
top: 50%;
transform: translateY(-50%);
color: #e51c24;
}
.custom_fast_search_result {
top: calc(100% + 1px);
position: absolute;
left: 0;
right: 0;
padding: 0;
margin: 0;
border: 1px solid #d7d7d7;
background: #ffffff;
z-index: 999;
max-height: 400px;
overflow: auto;
}
.search-result-products .repeat-item {
padding: 6px;
border-bottom: 1px dotted #d7d7d7;
}
.search-result-products .repeat-item .search-product {
display: flex;
gap: 5px;
}
.search-result-products .repeat-item .search-product .search-product__box-img img {
height: 65px;
object-fit: contain;
margin: auto;
}
.search-result-products .repeat-item .search-product .search-product__box-content .search-product-title {
font-size: 14px;
font-weight: 400;
line-height: 1.5;
margin-bottom: 5px;
}
.search-result-products .repeat-item .search-product .search-product__box-content .search-product-price .amount {
font-weight: 600;
color: red;
}Lưu ý:
- Đảm bảo font Ionicons đã được thêm vào website. Bạn có thể tải từ Ionicons hoặc sử dụng CDN.
- Thay đổi màu sắc theo ý của bạn
Bước 2: Thêm Code PHP Cho Chức Năng Tìm Kiếm
Thêm đoạn code PHP sau vào file functions.php của theme để tạo shortcode và xử lý tìm kiếm AJAX:
// Tạo shortcode để hiển thị form tìm kiếm
function custom_product_search_shortcode() {
ob_start();
?>
<form id="custom_search_form" class="form-inline" method="get" autocomplete="off">
<div class="form-group input-search">
<input type="text" id="search_query" name="s" class="custom_fast_search_input" placeholder="Nhập tên sản phẩm" required="">
</div>
<ul class="custom_fast_search_result" style="display: none;">
<a class="read-more-products" href="#" style="display: none;">Xem thêm</a>
</ul>
</form>
<script type="text/javascript">
jQuery(document).ready(function($) {
var query = '';
var offset = 10;
var loading = false;
$('#search_query').on('input', function() {
query = $(this).val();
if(query.length >= 3) {
$.ajax({
url: '<?php echo admin_url("admin-ajax.php"); ?>',
type: 'POST',
data: {
action: 'custom_search_action',
query: query,
offset: 0,
},
success: function(response) {
$('.custom_fast_search_result').html(response).show();
$('.read-more-products').show();
},
error: function() {
console.log("AJAX request failed");
}
});
} else {
$('.custom_fast_search_result').hide();
$('.read-more-products').hide();
}
});
$(document).on('click', '.read-more-products', function(e) {
e.preventDefault();
if (loading) return;
loading = true;
$('.read-more-products').hide();
$.ajax({
url: '<?php echo admin_url("admin-ajax.php"); ?>',
type: 'POST',
data: {
action: 'custom_search_action',
query: query,
offset: offset,
},
success: function(response) {
if (response.indexOf('Xem thêm') !== -1) {
$('.custom_fast_search_result').append(response);
offset += 10;
} else {
$('.read-more-products').hide();
}
loading = false;
},
error: function() {
console.log("AJAX request failed");
loading = false;
}
});
});
$(document).on('click', function(e) {
if (!$(e.target).closest('#custom_search_form').length) {
$('.custom_fast_search_result').hide();
}
});
});
</script>
<?php
return ob_get_clean();
}
add_shortcode('custom_product_search', 'custom_product_search_shortcode');
// Xử lý tìm kiếm qua AJAX và trả về sản phẩm
function custom_product_search_handler() {
$query = sanitize_text_field($_POST['query']);
$offset = isset($_POST['offset']) ? intval($_POST['offset']) : 0;
$args = [
'post_type' => 'product',
'posts_per_page' => 10,
'offset' => $offset,
's' => $query,
];
$product_query = new WP_Query($args);
$total_results = $product_query->found_posts;
if ($product_query->have_posts()) {
$shop_url = esc_url(get_permalink(wc_get_page_id("shop")));
if ($offset === 0) {
echo '<font class="tkw_fast_search_loading"><a href="' . $shop_url . '?s=' . urlencode($query) . '" class="view-all-results" target="_blank">Xem tất cả</a> <b>(' . $total_results . ')</b> kết quả với từ khóa: <b>' . esc_html($query) . '</b> </font>';
}
echo '<ul class="search-result-products">';
while ($product_query->have_posts()) {
$product_query->the_post();
$product = wc_get_product(get_the_ID());
$image = get_the_post_thumbnail(get_the_ID(), 'thumbnail');
$title = get_the_title();
$price = $product->get_price_html();
echo '<li class="repeat-item">';
echo '<a class="search-product" href="' . get_permalink() . '">';
echo '<div class="search-product__box-img">' . $image . '</div>';
echo '<div class="search-product__box-content">';
echo '<h4 class="search-product-title">' . $title . '</h4>';
echo '<div class="search-product-price">' . $price . '</div>';
echo '</div>';
echo '</a>';
echo '</li>';
}
echo '</ul>';
if ($offset + 10 < $total_results) {
echo '<a class="read-more-products" href="#">Xem thêm</a>';
} else {
echo '<a class="read-more-products" href="#" style="display: none;">Xem thêm</a>';
}
} else {
echo '<div class="box-not-found"><p>Không tìm thấy sản phẩm.</p></div>';
}
wp_reset_postdata();
wp_die();
}
add_action('wp_ajax_custom_search_action', 'custom_product_search_handler');
add_action('wp_ajax_nopriv_custom_search_action', 'custom_product_search_handler');Bước 3: Sử dụng Shortcode để chèn thêm ô tìm kiếm sản phẩm
Sau khi thêm code vào functions.php, bạn có thể chèn ô tìm kiếm vào bất kỳ vị trí nào trên website bằng shortcode: [custom_product_search]

Bước 4: Kiểm tra và tùy chỉnh thêm ô tìm kiếm sản phẩm
- Kiểm tra: Truy cập website, nhập từ khóa vào ô tìm kiếm và kiểm tra kết quả hiển thị.
- Mở rộng thêm:
- Điều chỉnh CSS để thay đổi màu sắc, kích thước, hoặc bố cục.
- Sửa code PHP để thêm các trường như danh mục sản phẩm hoặc bộ lọc nâng cao.
Lời kết
Việc thêm ô tìm kiếm sản phẩm không sử dụng plugin không chỉ giúp website nhẹ hơn mà còn mang lại sự linh hoạt trong tùy chỉnh. Với đoạn code CSS và PHP trên, bạn có thể dễ dàng tích hợp một ô tìm kiếm sản phẩm chuyên nghiệp, hỗ trợ AJAX và hiển thị kết quả tức thời. Hãy thử áp dụng ngay hôm nay để nâng cao trải nghiệm mua sắm trên website của bạn! Bên cạnh đó chúng tôi hiện đang cung cấp dịch vụ thiết kế website, đăng ký tên miền và web hosting rất mong được đồng hành cùng với các bạn. Liên hệ ngay để biết thêm thông tin chi tiết về dịch vụ cũng như chi phí. Tham khảo các mẫu website mới nhất tại kho giao diện.
Nếu bạn cần thêm hướng dẫn hoặc muốn tùy chỉnh code, hãy liên hệ lại với chúng tôi qua hotline/zalo: 0984.056.777. Hẹn các bạn ở bài viết hướng dẫn tiếp theo, nhớ theo dõi Digitech để biết được nhiều mẹo hay trong WordPress!













