TỔNG QUAN
WP Elasticsearch Giải Quyết Vấn Đề Gì?
- ⏱️ Website chậm chạp khi tìm kiếm với hàng nghìn bài viết/sản phẩm?
- 🔍 Khách hàng không tìm thấy nội dung dù gõ đúng từ khóa?
- 📉 Trải nghiệm kém khi filter nhiều điều kiện phức tạp?
- 🐌 Database quá tải khi có nhiều truy vấn đồng thời?
- ⚠️ Mất hàng giờ để query báo cáo, thống kê từ SQL?
WP Elasticsearch là giải pháp chuyên nghiệp giúp bạn:
- ⚡ Tăng tốc tìm kiếm lên 100 lần - Kết quả hiển thị tức thì dù hàng triệu records
- 🎯 Tìm kiếm thông minh - Full-text search, gõ sai chính tả vẫn tìm được
- 🔄 Đồng bộ real-time - Cập nhật ngay khi thay đổi nội dung WordPress/WooCommerce
- 📊 Thay thế SQL phức tạp - Giảm tải database 70-90%, query nhanh gấp 5-10 lần
- 💪 Ổn định & bảo mật - 3 phương thức index: AJAX (Nonce), Cron (Token), CLI (Anti-timeout)
Tính Năng Nổi Bật
⚡ Hiệu Suất Vượt Trội
- Tìm kiếm tức thì với hàng triệu records
- Thay thế SQL, giảm tải database 70-90%
- Query phức tạp nhanh gấp 5-10 lần
- Không làm chậm website gốc
🔄 Đồng Bộ Đa Dạng
- Sản phẩm (products) - Hoàn chỉnh
- Danh mục (terms) - Đang phát triển
- Đơn hàng (orders) - Đang phát triển
- Người dùng (users) - Đang phát triển
🛡️ Bảo Mật & An Toàn
- AJAX Mode: Nonce security
- Cron Mode: Token chống spam
- CLI Mode: Chống timeout
- Không làm mất dữ liệu gốc
📊 Quản Lý Dễ Dàng
- Giao diện trực quan, dễ sử dụng
- Test API trực tiếp với JSON Editor
- Generate cURL command tự động
- Console logs theo dõi real-time
🔍 Frontend Search Shortcode
[es_search]— thanh tìm kiếm ngoài frontend- Gợi ý real-time + phân trang kết quả
- Grid responsive, keyboard navigation
- Đa ngôn ngữ, hỗ trợ guest users
Yêu Cầu Cài Đặt
| Yêu cầu | Phiên bản tối thiểu | Khủyến nghị |
|---|---|---|
| WordPress | 5.0+ | Phiên bản mới nhất |
| WooCommerce | 3.0+ | Phiên bản mới nhất |
| PHP | 7.4+ | PHP 8.0 trở lên |
| Elasticsearch | 7.x | 7.x hoặc 8.x |
| RAM Server | 256MB | 512MB+ cho >10,000 sản phẩm |
Nếu bạn chưa có Elasticsearch, vui lòng liên hệ admin server để cài đặt. Plugin này chỉ đồng bộ dữ liệu, không bao gồm việc cài đặt Elasticsearch.
BẮT ĐẦU SỬ DỤNG
Bước 1: Kích Hoạt Plugin
- Vào WordPress Admin → Plugins
- Tìm WP Elasticsearch
- Click Activate
- ✅ Tạo cơ sở dữ liệu theo dõi
- ✅ Bật chế độ cập nhật tự động
- ✅ Chuẩn bị sẵn sàng sử dụng
Bước 2: Kiểm Tra Menu
Sau khi kích hoạt, bạn sẽ thấy menu Elasticsearch trên thanh quản trị:
| 📦 Index Product | Đồng bộ sản phẩm WooCommerce lên Elasticsearch |
| 🏷️ Index Term | Index danh mục sản phẩm (đang phát triển) |
| 🛒 Index Order | Index đơn hàng (đang phát triển) |
| 🔍 Test Search | Test query Elasticsearch trực tiếp với JSON Editor |
| ⚖️ Weighting | Quản lý độ ưu tiên (weight) của từng field khi tìm kiếm |
| ⚙️ Config | Cấu hình kết nối và cài đặt Elasticsearch |
| 📊 Log | Xem nhật ký hoạt động và debug |
CẤU HÌNH CHI TIẾT
Trang Config có 9 phần cấu hình theo thứ tự từ trên xuống dưới:
3.1. List Module (Chọn Loại Dữ Liệu Cần Đồng Bộ)
| Module | Mô tả | Trạng thái |
|---|---|---|
| Product | Sản phẩm WooCommerce | Đã hoàn thiện |
| Term | Danh mục sản phẩm | Đang phát triển |
| Order | Đơn hàng | Đang phát triển |
| User | Người dùng | Đang phát triển |
3.2. Product Configuration (Cấu Hình Sản Phẩm)
Index Settings (Cài Đặt Index)
| Index Name |
Tên index sản phẩm (ví dụ: products)⚠️ QUAN TRỌNG: Tên này sẽ được thêm Index Prefix phía trước! Nếu Index Prefix là web_wp_ và Index Name là products→ Index thực tế trên ES sẽ là: web_wp_products
|
| Batch Size |
Số sản phẩm xử lý mỗi lần (mặc định: 100) - Website nhỏ (<5K sản phẩm): 50-100 - Website vừa (5-20K sản phẩm): 100-200 - Website lớn (>20K sản phẩm): 200-500 |
Indexable Post Statuses (Trạng Thái Sản Phẩm Được Đồng Bộ)
Chọn trạng thái sản phẩm nào sẽ được đồng bộ lên Elasticsearch:
- publish - Sản phẩm đã xuất bản (nên chọn)
- draft - Bản nháp (tùy nhu cầu)
- pending - Chờ duyệt (tùy nhu cầu)
- private - Riêng tư (tùy nhu cầu)
3.3. General Configuration (Cấu Hình Kết Nối Elasticsearch)
| Elasticsearch URL |
URL server Elasticsearch:http://localhost (local)http://192.168.1.100 (IP server)https://domain.com (domain)
|
| Port | Cổng kết nối (mặc định: 9200) |
| Authentication |
No Auth: Không cần username/password Basic Auth: Cần username và password |
| Username | Tên đăng nhập (nếu dùng Basic Auth) |
| Password | Mật khẩu (nếu dùng Basic Auth) |
| Index Prefix |
QUAN TRỌNG: Tiền tố thêm vào TẤT CẢ các index Ví dụ: Nếu Index Prefix là web_wp_→ Index Product: web_wp_products→ Index Term: web_wp_terms→ Index Order: web_wp_orders💡 Mục đích: Phân biệt nhiều website dùng chung 1 Elasticsearch server |
| Timeout |
Thời gian chờ kết nối (giây, mặc định: 30) Tăng lên nếu server Elasticsearch chậm |
3.4. Index Mode (Chế Độ Đánh Index) ⭐ QUAN TRỌNG
| Chế Độ | Cách Hoạt Động | Bảo Mật | Dùng Khi Nào? |
|---|---|---|---|
| AJAX Mode |
Click nút "Index Product" trên Admin Panel Sử dụng admin-ajax.php
|
Nonce Verification Chỉ Admin mới chạy được |
✅ Website nhỏ (<5K sản phẩm) ✅ Đánh index thủ công ✅ Không cần setup cron |
| CLI Mode |
Chạy qua WP-CLI command:wp es index products
|
Server-side Only Không timeout, chống gián đoạn |
✅ Website trung/lớn (>10K sản phẩm) ✅ Chạy trong Server/SSH ✅ Setup cron job tự động ✅ VPS/Dedicated server |
| Cron API Mode |
Gọi REST API endpoint:/wp-json/sync/es?token=xxx
|
Security Token Required Token bảo vệ API endpoint |
✅ Shared hosting (không có SSH) ✅ Muốn gọi từ bên ngoài (cURL) ✅ Chạy song song nhiều batch ✅ Setup cPanel Cron Jobs |
Chi Tiết Từng Mode:
Cách sử dụng:
- Chọn Index Mode: Ajax trong Config
- Vào trang Index Product
- Click nút "Index Product"
- Đợi tiến trình chạy xong
Ưu điểm:
- ✅ Đơn giản, không cần setup gì thêm
- ✅ Xem progress bar realtime
- ✅ An toàn với Nonce verification
Nhược điểm:
- ❌ Có thể timeout với website lớn
- ❌ Phải ngồi đợi, không tự động
Cách sử dụng:
- Chọn Index Mode: CLI trong Config
- SSH vào server
- Chạy command:
# Index 1 batch (100 sản phẩm)
wp es index products
# Index với batch size tùy chỉnh
wp es index products --batch-size=500
# Index liên tục đến hết
wp es index products --continuous
# Bỏ qua lock check
wp es index products --force
Setup Cron Job (tự động mỗi phút):
# Crontab
* * * * * cd /path/to/wordpress && wp es index products >/dev/null 2>&1
Ưu điểm:
- ✅ Không bao giờ timeout
- ✅ Chạy nền, tự động với cron
- ✅ Hiệu suất cao nhất
- ✅ Xử lý được hàng triệu sản phẩm
Nhược điểm:
- ❌ Cần SSH access
- ❌ Phải cài WP-CLI
- ❌ Shared hosting thường không hỗ trợ
Cách sử dụng:
- Chọn Index Mode: Cron API trong Config
- Click "🔑 Generate Token" để tạo Security Token
- Copy Cron URL (có dạng:
/wp-json/sync/es?token=xxx) - Setup trong cPanel Cron Jobs hoặc dùng cURL
Ví dụ cURL:
curl -X GET "https://your-site.com/wp-json/sync/es?token=YOUR_TOKEN"
Setup trong cPanel Cron Jobs (chạy mỗi 5 phút):
*/5 * * * * curl -X GET "https://your-site.com/wp-json/sync/es?token=YOUR_TOKEN" >/dev/null 2>&1
Ưu điểm:
- ✅ Hoạt động trên Shared Hosting
- ✅ Không cần SSH
- ✅ Gọi từ bất kỳ đâu (cURL, cron service)
- ✅ Chạy song song nhiều batch
- ✅ Bảo mật bằng Security Token
Nhược điểm:
- ❌ Phải bảo mật token cẩn thận
- ❌ Có thể timeout nếu hosting giới hạn
3.5. Synchronization Mode (Chế Độ Đồng Bộ)
| Chế Độ | Hoạt Động | Dùng Khi Nào? |
|---|---|---|
| Real-time Sync |
Tự động cập nhật Elasticsearch ngay khi: - Thêm/sửa/xóa sản phẩm - Thay đổi giá, stock - Cập nhật category, tags |
✅ Website nhỏ/vừa ✅ Cần dữ liệu luôn mới nhất ✅ Ít thao tác bulk update |
| Queue Mode |
Đánh dấu sản phẩm cần sync Chạy hàng loạt sau bằng Cron/CLI |
✅ Website lớn ✅ Import hàng loạt thường xuyên ✅ Tiết kiệm tài nguyên |
3.6. Search Language (Ngôn Ngữ Tìm Kiếm)
| Ngôn Ngữ | Analyzer | Tính Năng |
|---|---|---|
| Vietnamese (Mặc định) |
vietnamesevietnamese_foldedvietnamese_edge
|
✅ Tìm có dấu & không dấu ✅ 60 stop words tiếng Việt ✅ Autocomplete thông minh ✅ Multi-field (.vietnamese, .folded, .autocomplete) |
| English |
standardsnowball
|
✅ Stemming (run → running → runs) ✅ English stop words ✅ Standard tokenizer |
1. Save Settings
2. Xóa index cũ (Delete Index)
3. Create Mapping lại
4. Index dữ liệu từ đầu
3.7. Mapping Settings (Cài Đặt Cấu Trúc Index)
| Cài Đặt | Giá Trị Mặc Định | Dùng Khi Nào? |
|---|---|---|
| Number of Shards | 1 |
Tăng lên 3-5 nếu >100K sản phẩm Phân tán dữ liệu, tăng hiệu suất |
| Number of Replicas | 0 |
Tăng lên 1-2 nếu có nhiều ES node Tạo bản sao backup |
| Total Field Limit | 15000 |
Tăng nếu sản phẩm có rất nhiều fields/attributes ES giới hạn mặc định 1000 fields |
| Max Result Window | 1000000 |
Số kết quả tối đa có thể trả về (10000-10000000) Tăng nếu cần search/scroll nhiều kết quả |
3.8. Debug Settings (Cài Đặt Debug)
| Enable Logging |
Bật/tắt ghi log vào database Bật: Ghi lại tất cả lỗi và thông tin hoạt động → xem tại Elasticsearch → Log Tắt: Không ghi log, tiết kiệm database |
3.9. Cron Job Configuration (Cấu Hình Cron)
| Cài Đặt | Mặc Định | Mô Tả |
|---|---|---|
| Cron Interval | 1 phút | Tần suất cron kiểm tra records chờ xử lý (1-1440 phút) |
| Batch Size | 500 | Số records xử lý mỗi lần chạy batch (1-10000) |
| Security Key | Tự tạo |
Token bảo mật cho Cron API endpoint Click "Generate" để tạo key mới |
Cron Endpoint Information
Sau khi tạo Security Key, plugin sẽ hiển thị:
- Cron URL: Đường dẫn API endpoint (dạng
/wp-json/sync/es?token=xxx) - Example: Lệnh crontab mẫu để copy
QUY TRÌNH INDEX LẦN ĐẦU
📍 Truy cập: WordPress Admin → Elastic Search → Config
- Chọn Product trong List Module
- Nhập Index Name trong Product Configuration (ví dụ:
products) - Điền thông tin Elasticsearch URL, Port, Auth trong General Configuration
- Chọn Index Mode: AJAX / CLI / Cron API (đọc phần 3.4 để chọn đúng)
- Click "Save"
Ví dụ: Index Prefix =
web_wp_, Index Name = products → Index thực tế: web_wp_products
📍 Truy cập: WordPress Admin → Elastic Search → Index Product
- Click nút "📋 Create Mapping"
- Đợi 5-10 giây
- Thấy thông báo "✅ Successfully" là xong!
Vẫn ở trang Index Product:
- Click nút "📦 Prepare Index Data"
- Plugin sẽ đánh dấu tất cả sản phẩm cần đồng bộ
- Bạn sẽ thấy số lượng sản phẩm Pending (chờ index)
Cách thực hiện tùy vào Index Mode bạn đã chọn ở Bước 1:
🖱️ Nếu dùng AJAX Mode:
- Vẫn ở trang Index Product
- Click nút "▶️ Index Product"
- Theo dõi thanh tiến trình (progress bar)
- Đợi đến khi hoàn thành 100%
⌨️ Nếu dùng CLI Mode:
- SSH vào server
- Di chuyển đến thư mục WordPress
- Chạy command:
# Index liên tục đến hết
wp es index products --continuous
# Hoặc setup cron chạy mỗi phút (khuyến nghị)
* * * * * cd /path/to/wordpress && wp es index products >/dev/null 2>&1
🌐 Nếu dùng Cron API Mode:
- Đảm bảo đã tạo Security Token ở Config (Bước 1)
- Copy Cron URL từ Config page
- Setup trong cPanel Cron Jobs:
*/5 * * * * curl -X GET "https://your-site.com/wp-json/sync/es?token=YOUR_TOKEN" >/dev/null 2>&1
Hoặc chạy thủ công bằng cURL để test:
curl -X GET "https://your-site.com/wp-json/sync/es?token=YOUR_TOKEN"
📍 Truy cập: WordPress Admin → Elastic Search → Index Product
Xem thống kê trong Statistics panel:
- DB Count: Tổng số sản phẩm trong Database
- ES Count: Tổng số sản phẩm trên Elasticsearch
- Success: Số sản phẩm index thành công
- Failed: Số sản phẩm lỗi (nếu có)
- Pending: Số sản phẩm chờ index (phải = 0)
- Mọi thay đổi sản phẩm (thêm/sửa/xóa) sẽ tự động sync nếu bật Real-time Sync
- Plugin tự động verify và sửa lỗi mỗi giờ (Auto Verify & Sync)
- Bạn có thể xem log chi tiết tại: Elastic Search → Log
AUTO VERIFY & SYNC
6.1. Giới Thiệu
Auto Verify & Sync là tính năng mới v1.4.2 - tự động kiểm tra và đồng bộ dữ liệu giữa Database và Elasticsearch mỗi giờ.
6.2. Quy Trình Hoạt Động
- Kiểm Tra Tổng Số (Verify Total Count)
- So sánh tổng số sản phẩm trên Database vs Elasticsearch
- Nếu khác: tiếp tục bước 2
- Phát Hiện Sản Phẩm Thiếu (Find Missing Products)
- Tìm sản phẩm tồn tại trên DB nhưng không có trên ES
- Đánh dấu để reindex tự động
- Phát Hiện Sản Phẩm Thừa (Find Extra Products)
- Tìm sản phẩm tồn tại trên ES nhưng bị xóa trên DB
- Xóa tự động khỏi ES
- Sửa Sản Phẩm Lỗi (Fix Failed Products)
- Tìm sản phẩm có status=2 (lỗi) vẫn tồn tại trên ES
- Xóa khỏi ES để không ảnh hưởng
- Ghi Log (Database Logging)
- Ghi lại tất cả hoạt động vào database
- Xem chi tiết từ Admin → Elasticsearch → Log
6.3. Xem Nhật Ký
Truy cập WordPress Admin → Elasticsearch → Log để xem:
- 📝 Tất cả hoạt động verify & sync
- 🔍 Tìm kiếm theo từ khóa
- 🏷️ Lọc theo loại log
- 📅 Lọc theo ngày
- ⬆️⬇️ Sắp xếp theo cột
CẬP NHẬT TỰ ĐỘNG
Plugin Tự Động Cập Nhật Khi Bạn:
📝 Thêm/Sửa Sản Phẩm
- Tạo sản phẩm mới
- Chỉnh sửa thông tin
- Đổi giá, tên, mô tả
- Cập nhật hình ảnh
🏷️ Quản Lý Phân Loại
- Thay đổi danh mục
- Thêm/bớt tags
- Cập nhật thuộc tính
- Đổi brand
📦 Cập Nhật Kho
- Thay đổi số lượng
- Đặt trạng thái stocked
- Cập nhật SKU
- Quản lý variations
🗑️ Xóa Sản Phẩm
- Chuyển vào thùng rác
- Xóa vĩnh viễn
- Khôi phục từ rác
- Tự động dọn dẹp
Khi bạn click "Cập nhật" sản phẩm trong WordPress:
- ✅ Dữ liệu được đánh dấu cập nhật ngay lập tức
- ✅ Elasticsearch nhận thông tin sau vài giây
- ✅ Khách hàng tìm kiếm thấy dữ liệu mới luôn
Bạn không cần chạy lại đồng bộ thủ công!
🎯 SEARCH WEIGHTING (ƯU TIÊN TÌM KIẾM)
1. Truy Cập Weighting Page
📍 Vào: WordPress Admin → Elasticsearch → Weighting
2. Các Tab Quản Lý
| Tab | Nội Dung | Trạng Thái |
|---|---|---|
| Product | Field sản phẩm (title, content, SKU, taxonomy, meta) | ✅ Hoàn chỉnh |
| Term | Field danh mục/tag (name, description, slug) | ✅ Hoàn chỉnh |
| Order | Field đơn hàng | 🔧 Coming soon |
| User | Field người dùng (username, email, display_name) | ✅ Hoàn chỉnh |
3. Cấu Hình Product Weighting
Mỗi field có slider 1-100:
| Field | Default Weight | Boost | Ý Nghĩa |
|---|---|---|---|
post_title |
80 | 8.0 | Tên sản phẩm - rất quan trọng |
post_excerpt |
50 | 5.0 | Mô tả ngắn |
post_content |
30 | 3.0 | Nội dung chi tiết |
post_author |
10 (disabled) | 1.0 | Tác giả - ít quan trọng |
| Taxonomy | Default Weight | Mô Tả |
|---|---|---|
product_cat |
60 | Danh mục sản phẩm |
product_tag |
40 | Thẻ tag |
| Custom taxonomy | 30 | Brand, Color, Size... |
| Meta Key | Default Weight | Mô Tả |
|---|---|---|
_sku |
90 | Mã SKU - ưu tiên cao nhất |
_product_attributes |
30 | Các thuộc tính |
| Custom meta | - | Tự thêm bằng nút "Add Meta Field" |
- Fuzziness: Auto / 0 / 1 / 2 (cho phép sai chính tả)
- Minimum Should Match: 50% / 75% / 100% (% từ khóa phải khớp)
4. Hướng Dẫn Weight
| Mức Độ | Weight | Boost | Dùng Cho |
|---|---|---|---|
| Very High | 80-100 | 8.0-10.0 | SKU, Title - thông tin quan trọng nhất |
| High | 50-79 | 5.0-7.9 | Short Description, Category |
| Medium | 20-49 | 2.0-4.9 | Content, Tags, Attributes |
| Low | 1-19 | 0.1-1.9 | Author, Custom meta ít quan trọng |
5. Query 3 Tầng
Weighting system tự động build query thông minh:
Khớp đúng cụm từ có boost cao nhất:
{
"multi_match": {
"query": "áo thun",
"type": "phrase",
"fields": ["post_title.vietnamese^8", "post_title.folded^5"],
"boost": 3
}
}
Khớp tất cả từ (có thể sai vài ký tự):
{
"multi_match": {
"query": "áo thun",
"type": "best_fields",
"fuzziness": "AUTO",
"minimum_should_match": "75%"
}
}
Khớp 1 hoặc nhiều từ trên nhiều field:
{
"multi_match": {
"query": "áo thun",
"type": "cross_fields",
"operator": "or"
}
}
6. Sử Dụng Weighting
jQuery.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'es_frontend_search',
nonce: nonce,
keyword: 'áo thun',
page: 1,
per_page: 10
},
success: function(response) {
console.log(response.data.products);
console.log(response.data.total);
}
});
$search_pr = new SEARCH_PR();
$result = $search_pr->search_products('áo thun', 1, 10);
if ($result['success']) {
$products = $result['data']['products'];
$total = $result['data']['total'];
foreach ($products as $product) {
echo $product['title'];
echo $product['score']; // Điểm số relevance
}
}
// Filter weighted fields
add_filter('es_search_weighted_fields', function($fields, $type, $language) {
if ($type === 'product') {
$fields[] = 'custom_field^10'; // Thêm field custom
}
return $fields;
}, 10, 3);
// Filter query
add_filter('es_search_products_query', function($query, $keyword, $page, $per_page) {
$query['size'] = 20; // Override per_page
return $query;
}, 10, 4);
- Tăng weight cho field quan trọng với bạn (SKU, Title)
- Giảm weight cho field ít liên quan (Author)
- Disable field không cần search (checkbox off)
- Save Settings sau khi thay đổi
XỬ LÝ SỰ CỐ
Plugin Tự Động Sửa Những Vấn Đề Này:
Nguyên nhân: Có thể do lỗi mạng, server quá tải khi đồng bộ...
Giải pháp: Plugin tự động phát hiện và đồng bộ lại sản phẩm thiếu.
Nguyên nhân: Bạn đã xóa sản phẩm trong WooCommerce nhưng ES chưa xóa...
Giải pháp: Plugin tự động xóa sản phẩm không còn tồn tại.
Nguyên nhân: Một số sản phẩm fail nhiều lần...
Giải pháp: Plugin tự động dọn dẹp và thử đồng bộ lại.
Xem Nhật Ký Hoạt Động
Muốn biết plugin đã làm gì? Vào WordPress Admin → Elasticsearch → Log
- 📝 Xem tất cả hoạt động tự động
- 🔍 Tìm kiếm theo từ khóa
- 📊 Kiểm tra số liệu thống kê
- ⏰ Xem lịch sử theo ngày
TÙY BIẾN NÂNG CAO
| # | Nhóm | Action Hooks | Mô Tả |
|---|---|---|---|
| 1 | Product Save | save_post_product | Tất cả product saves (admin, REST, CLI, import, bulk edit, quick edit) |
| 2-4 | Post Meta |
updated_post_meta added_post_meta deleted_post_meta |
Thay đổi meta (giá, SKU, kích thước...) - không trigger save_post |
| 5 | Taxonomy | set_object_terms | Thay đổi danh mục, tag, brand, shipping class |
| 6-8 | Review |
comment_post deleted_comment transition_comment_status |
Thêm/xóa/thay đổi trạng thái review |
| 9-10 | Trash / Restore |
wp_trash_post untrashed_post |
Sản phẩm vào thùng rác / khôi phục - không trigger save_post |
| 11 | Delete | before_delete_post | Xóa vĩnh viễn sản phẩm hoặc variation |
| 12 | Variation | save_post_product_variation | Variation thay đổi → re-index parent product |
| 13-14 | Stock |
woocommerce_product_set_stock woocommerce_product_set_stock_status |
Thay đổi số lượng / trạng thái tồn kho |
| 15-16 | Scheduled Sale |
wc_after_products_starting_sales wc_after_products_ending_sales |
Giá sale theo lịch bắt đầu/kết thúc (WooCommerce cron) |
- Các hooks đăng ký product cần sync vào global array
- Cuối request (shutdown hook), tất cả products được xử lý 1 lần duy nhất
- Tự động merge khi 1 product trigger nhiều hooks trong cùng 1 request
- Action
deletedcó priority cao nhất - không bị override
WP-CLI COMMANDS
7.1. Giới Thiệu
WP-CLI cho phép index từ command line - lý tưởng cho:
- Server operations
- Cron jobs
- CI/CD pipelines
- Large-scale indexing
7.2. Index Products
wp es index products
# Custom batch size (default: 100)
wp es index products --batch-size=500
# Continuous mode - process all batches until complete
wp es index products --batch-size=500 --continuous
# Force start (bỏ qua lock check)
wp es index products --force
# Combine options
wp es index products --batch-size=200 --continuous --force
--continuous flag:
- Không có flag (mặc định): Xử lý 1 batch rồi dừng → Thích hợp cho cron job gọi mỗi phút
- Có flag
--continuous: Xử lý tất cả batch cho đến hết → Thích hợp cho chạy manual một lần
7.3. Get Statistics
wp es stats
ELASTICSEARCH API TEST
Hỗ trợ JSON Editor, cURL Command generator và Response viewer.
Truy cập: Elasticsearch > Test Search
8.1. Tính Năng
JSON Editor Tab
- Code Editor: Syntax highlighting cho JSON
- Format JSON: Tự động format code đẹp
- Load Sample: Tải query mẫu theo type
- Validation: Kiểm tra JSON hợp lệ trước khi gửi
cURL Command Tab
- Auto Generate: Tự động tạo cURL từ JSON
- Full Config: Bao gồm URL, auth, headers, body
- Copy Clipboard: Click để copy command
- Terminal Ready: Format chuẩn để chạy
Response Viewer
- Body Tab: Hiển thị JSON với syntax highlighting
- Headers Tab: Xem response headers
- Search in Response: Tìm kiếm trong kết quả
- Navigation: Di chuyển giữa kết quả
8.2. Cách Sử Dụng - Gửi Request
- Method: POST hoặc GET
- Type: Product (Term/Order đang phát triển)
{
"query": {
"bool": {
"must": [
{
"match": {
"post_title": "áo"
}
}
]
}
},
"size": 10,
"from": 0
}
Hoặc click "Load Sample" để tải query mẫu, sau đó click "Format JSON" để format code.
Click "Send Request" và xem kết quả trong Response panel.
8.3. Generate cURL Command
- Nhập JSON query trong JSON Editor tab
- Chuyển sang tab "cURL Command"
- Xem cURL command được tạo tự động
- Click "Copy cURL" để copy
- Paste vào terminal để chạy
curl -X POST \
"https://domain.com:9200/wp_products/_search" \
-H "Content-Type: application/json" \
-u "username:password" \
-d '{
"query": {
"match": {
"post_title": "áo"
}
},
"size": 10
}'
8.4. Tìm Kiếm Trong Response
- Nhập từ khóa vào ô "Search in response..."
- Kết quả sẽ được highlight màu vàng
- Dùng nút ↑ ↓ để navigate giữa kết quả
8.5. Ví Dụ Queries
{
"query": {
"match": {
"post_title": "samsung galaxy"
}
}
}
{
"query": {
"bool": {
"must": [
{"match": {"post_title": "áo"}}
],
"filter": [
{"range": {"regular_price": {"gte": 100000}}}
]
}
}
}
{
"size": 0,
"aggs": {
"categories": {
"terms": {
"field": "category_ids",
"size": 10
}
}
}
}
FRONTEND SEARCH SHORTCODE
[es_search] hiển thị thanh tìm kiếm Elasticsearch ngoài frontend cho khách truy cập website.
Cách Sử Dụng
Chèn shortcode vào bất kỳ trang/bài viết nào:
[es_search]
Attributes
| Attribute | Mặc Định | Mô Tả |
|---|---|---|
type |
product |
Loại dữ liệu: product, order, term, user |
per_page |
10 |
Số kết quả mỗi trang (1-100) |
columns |
3 |
Số cột hiển thị grid: 2, 3, 4 |
placeholder |
Search products... |
Text placeholder ô tìm kiếm |
Ví Dụ
[es_search type="product" per_page="12" columns="4" placeholder="Tìm sản phẩm..."]
[es_search type="product" per_page="6" columns="2"]
Tính Năng
🔍 Gợi Ý Tìm Kiếm
- Dropdown gợi ý real-time khi gõ từ 2 ký tự
- Debounce 300ms tránh spam request
- Arrow Up/Down di chuyển, Enter chọn, Escape đóng
📊 Kết Quả Grid
- Card sản phẩm: ảnh, tên, giá, link
- Grid responsive 2/3/4 cột
- Phân trang Prev/Next với số trang
⚡ Đa Instance
- Nhiều shortcode trên cùng trang
- Mỗi instance có state độc lập
- CSS & JS tách file riêng
🌍 Đa Ngôn Ngữ
- i18n đầy đủ qua wp_localize_script
- Hỗ trợ cả logged-in và guest
- 5 chuỗi frontend đa ngôn ngữ
AJAX Actions
| Action | Mô Tả |
|---|---|
es_shortcode_suggestions |
Lấy danh sách gợi ý (keyword, type, limit) |
es_shortcode_search |
Tìm kiếm full (keyword, type, page, per_page) |
MÃ TRẠNG THÁI
10.1. Product Status Codes
| Code | Tên | Màu | Ý Nghĩa |
|---|---|---|---|
| 0 | Pending | 🔵 Xanh dương | Chờ đánh index |
| 1 | Success | 🟢 Xanh lá | Đã index thành công |
| 2 | Failed | 🔴 Đỏ | Index thất bại |
| 5 | Processing | 🟡 Vàng | Đang xử lý |
📝 CHANGELOG
Version 1.6.3 (19/03/2026) - LATEST!
- New Frontend Search Shortcode
[es_search]— thanh tìm kiếm Elasticsearch ngoài frontend - New Hỗ trợ 4 attributes:
type,per_page,columns,placeholder - New Suggestions dropdown — gợi ý real-time khi gõ từ 2 ký tự (debounce 300ms)
- New Kết quả dạng grid responsive với card sản phẩm (ảnh, tên, giá, link)
- New Phân trang đầy đủ Prev/Next, số trang, auto scroll về đầu kết quả
- New Mỗi shortcode instance hoạt động độc lập trên cùng trang
- New 2 AJAX actions:
es_shortcode_search,es_shortcode_suggestions(logged-in & guest) - Feature CSS & JS tách file riêng:
wpes-search.css,wpes-search.js - Feature Keyboard navigation (Arrow keys, Enter, Escape) cho suggestions
- i18n 5 chuỗi frontend đa ngôn ngữ qua
wp_localize_script
Version 1.6.2 (19/03/2026)
- Fix HEAD request timeout trong `call_api()` — thêm `CURLOPT_NOBODY => true`
- Fix `parse_response()` xử lý riêng HEAD response, không parse JSON
- Refactor `is_configured()` dual-purpose: trả về `$config` array hoặc `false`
- Refactor `check_index_exists()` dùng HEAD `index_exists()` thay vì loop `get_indices_stats()`
- Improved Bỏ 6 lần gọi `get_config()` thừa trong `create_mapping()`, `process_pending_syncs()`, 4 sync workers
- i18n Bổ sung 7 strings còn thiếu cho Test Search / Weighted Query panel vào `.pot`
- Fix Sửa msgid sai: "Request Body (JSON)" → "Request Body" trong `.pot`
Version 1.6.1 (13/02/2026)
- Improved Test Search JSON Editor - Hỗ trợ JSON comments (`//` và `/* */`)
- Fix Format JSON error với non-breaking space (ký tự )
- Improved Auto scroll về góc trái trên sau khi format JSON
- Improved Giữ syntax highlighting sau khi format
- New Enter key navigation cho search results trong Response panel
- New Shift + Enter để navigate ngược lại
- Improved Auto loop search results khi đến cuối
- Fix Loại bỏ zero-width characters khỏi JSON input
Version 1.6.0 (12/02/2026)
- Refactor Architecture Optimization - Chuẩn hóa AJAX → PR → DB pattern cho Weighting system
- Refactor Tách biệt logic: AJAX validate input → PR business logic → DB CRUD operations
- New Thêm 3 methods mới trong WEIGHTING_PR: get_weighting_config(), save_weighting_config(), reset_weighting_config()
- i18n Chuẩn hóa ngôn ngữ: Code comments tiếng Việt, UI messages tiếng Anh với __() function
- i18n Cập nhật wp-es.pot với 21 msgid mới cho weighting system (4 sections mới)
- Fix JS/AJAX parameter mismatch - admin.js gửi 'weighting' nhưng PHP nhận 'data'
- Fix Sửa duplicate validation trong reset_weighting() method
- Fix get_available_taxonomies() thiếu parameter $post_type (line 425)
- Fix DB method calls: save_weighting() → save_weighting_by_type()
- Improved Error handling với structured response array (success, message, data)
- Improved Code organization - Giảm trùng lặp logic giữa AJAX và PR layers
Version 1.5.0 (11/02/2026)
- New Vietnamese Search Support - 3 analyzer chuyên dụng (vietnamese, vietnamese_folded, vietnamese_edge)
- New Search Language Config - Chọn Vietnamese hoặc English analyzer
- New Search Weighting System - Quản lý độ ưu tiên (weight) của từng field khi tìm kiếm
- New Weighting Admin UI - 4 tabs (Product/Term/Order/User) với slider 1-100
- New 3-tier Weighted Query - Phrase match (boost x3) + All terms + Cross fields
- New Frontend Search API -
es_frontend_searchaction cho AJAX search - Feature Multi-field mapping cho Vietnamese (
.vietnamese,.folded,.autocomplete) - Feature 60 Vietnamese stop words + asciifolding với preserve_original
- Feature Edge n-gram autocomplete (min:2, max:15) cho tiếng Việt
- Improved Sample queries theo ngôn ngữ (Vietnamese/English)
- Cleanup Xóa "Search Product" khỏi Index Product page (có menu riêng)
- Cleanup Xóa
date_termsvàpost_passwordkhỏi mapping - i18n Thêm 10+ strings mới cho Weighting feature
Version 1.4.8 (11/02/2026)
- Fix Sửa README.html thiếu chi tiết 3 Index Mode (AJAX/CLI/Cron API)
- Docs Viết lại phần Cấu Hình Chi Tiết với 6 subsections rõ ràng
- Docs Thêm bảng so sánh 3 Index Mode: bảo mật, use cases, commands
- Docs Nêu rõ Index Name nằm ở Config page, không phải Index Product page
- Docs Quy trình Index lần đầu: 5 bước từ Config → Verify kết quả
- Docs Giải thích Index Prefix áp dụng cho TẤT CẢ indices
Version 1.4.7 (11/02/2026)
- Docs Cập nhật toàn bộ documentation theo code mới nhất (README.md)
- Docs Viết lại phần Cấu hình chi tiết cho 3 Index Mode: AJAX, CLI, Cron API
- Docs Thêm hướng dẫn cấu hình Product Configuration
- Docs Thêm Quy trình Index lần đầu rõ ràng từ Bước 1-5
- Fix Sửa thông tin sai lệch về Index Prefix và Index Name
Version 1.4.6 (11/02/2026)
- Fixed Sửa lỗi cursor nhảy về đầu khi nhập text trong JSON Editor
- Feature Collapsible JSON Viewer - Thu gọn/mở rộng JSON tree trong Response Body
- UI/UX Hiển thị ▶/▼ icons và preview (X items/keys) khi thu gọn
- Performance Tối ưu cursor position tracking với character offset
Version 1.4.5 (11/02/2026)
- New Thêm Elasticsearch API Test interface với JSON Editor
- New cURL Command Generator - auto generate cURL từ JSON query
- New Response Viewer với search-in-response feature
- New Tab switching: JSON Editor ↔ cURL Command
- UI/UX Modern code editor với syntax highlighting
- Feature Copy cURL command to clipboard với 1 click
Version 1.4.4 (11/02/2026)
🐛 Sửa Lỗi Nghiêm Trọng:
- 🔧 Fix 92 Products Infinite Loop Bug: Sửa lỗi 92 sản phẩm lặp vô hạn mỗi ngày
- Layer 1: Hook 15-16 (scheduled sales) thêm
get_post_type()validation - Layer 2:
es_sync_product()validate product tồn tại quaget_post() - Layer 3:
index_data()gọiremove_products_batch()khi empty post data - Root cause: Orphaned postmeta cho deleted products trigger scheduled sales hooks
- Layer 1: Hook 15-16 (scheduled sales) thêm
✨ Cải Tiến Error Handling:
- 🛡️ Index Mode Validation: Cải thiện validation và error messages
- Thay
showLockErrorWithForceStart()bằngshowNoti()+ state reset - Rút gọn error message: "Index mode must be %s (current: %s)"
- Thêm i18n support (English + Vietnamese)
- Validation hoàn toàn server-side
- Thay
🎨 Cải Tiến UI/UX:
- 📊 Progress Panel Improvements: Tối ưu hiển thị
- Lazy initialization: Chỉ tạo progress panel sau AJAX success đầu tiên
- Thêm loading overlay ngay khi bắt đầu indexing
- Fix positioning: Progress nằm giữa main buttons và Advanced Options
- Indexing Console luôn nằm dưới Progress Panel
- 🔘 Advanced Options Button States:
- Thêm
#reindex_all_productsvà#reindex_failed_productsvàodisableAllButtons() - Tất cả 7 buttons (5 main + 2 advanced) disable đồng thời khi indexing
- Advanced Options toggle không bị đẩy xuống
- Thêm
🌍 Đa Ngôn Ngữ:
- Thêm
indexModeMustBe: "Index mode must be %s (current: %s)" - Thêm mode labels: Ajax, CLI, Cron API
- Cập nhật
wp-es.pot,wp-es-vi_VN.po
📝 Files Modified:
hook.php- 3-layer validation for product syncprocess/product_pr.php- Cleanup invalid productsassets/js/admin.js- UI improvements & lazy initprocess/index.php- Shortened error messageslanguages/- Added i18n strings
Version 1.4.3 (08/01/2026)
⚡ Performance Optimization:
- 🚀 Cached Index Checking: Loại bỏ HEAD request chậm
- Thêm
check_index_exists()method trong PRODUCT_PR - Kiểm tra từ
get_indices_stats()raw_data đã load - Giảm thời gian load: 60s → <1s (98% faster)
- Thêm
- ⚡ Optimized get_status(): Không gọi ES API mỗi page load
- Trả về field
product_index_exists - Reuse cached data thay vì query lại
- Trả về field
- ✅ Smart Validation: index_data() kiểm tra mapping trước
- Ngăn indexing khi chưa có mapping
- Tránh lỗi "index not found"
🎨 UX Improvements:
- ✨ Instant UI Updates: JavaScript xóa warning ngay lập tức
- fadeOut() animation khi create mapping thành công
- Enable 7 buttons instantly (prepare, index, reset, delete, advanced...)
- Không reload page, chỉ AJAX refresh stats
- 🎯 Dynamic Notice Management: Xử lý cả template và dynamic notice
- Notice từ status-product.php template
- Notice tạo động trong JavaScript
- Smooth transitions với fadeOut()
🔧 Code Changes:
- 🔒 Strict Configuration: create_mapping() yêu cầu config
- Không còn default value 'wp_products'
- Báo lỗi nếu chưa có configuration
- 🧹 Code Cleanup: Xóa obsolete functions
- Removed:
has_mapping() - Removed:
set_mapping_status()
- Removed:
- 📦 Better Organization: Logic đúng chỗ
- CONFIG_PR::get_product_config()
- Removed JS to PHP data passing
🐛 Bug Fixes:
- Fixed: Warning notice vẫn hiển thị sau successful mapping
- Fixed: Dynamic notice không có ID để xóa
- Fixed: Page load 60s do HEAD request
📝 Files Modified:
process/product_pr.php- Added check_index_exists(), removed obsolete methodsadmin/product_ad.php- Uses product_index_exists fieldadmin/template-path/status-product.php- Added notice IDassets/js/admin.js- Instant UI updates, remove noticesprocess/config_pr.php- Added default config values
Version 1.4.2 (28/12/2025)
✨ New Features:
- 🔄 Auto Verify & Sync Process (VERIFY_PR Class): Tự động kiểm tra mỗi giờ
- Auto-detect missing products - Tìm sản phẩm bị thiếu trên ES
- Auto-detect extra products - Tìm sản phẩm thừa trên ES
- Auto-fix failed products - Xóa sản phẩm lỗi khỏi ES
- Comprehensive logging - Ghi log chi tiết tất cả hoạt động
- 📊 Database Logging System (LOG_PR Class): Lưu audit trail vĩnh viễn
- Ghi vào bảng
wp_es_logsthay vì console - Tên log có thể cấu hình để lọc
- Admin Log page hiển thị tất cả logs với search/filter
- Ghi vào bảng
- 🎯 Code Consolidation: Phương thức cha tập trung
is_index_enabled($type)- Kiểm tra index typeget_index_name($index_type)- Lấy tên index- Loại bỏ duplicate methods trong child classes
🔧 Improvements:
- Configuration-driven batch sizes - Đọc từ
max_rowsconfig - Logging system migration - Từ CONSOLE_PR sang LOG_PR
- Enhanced logging coverage - Ghi log tất cả verify operations
- Vietnamese translations - Đầy đủ dịch tiếng Việt
🐛 Bug Fixes:
- Fixed
ES_SETTINGundefined constant - Fixed
get_api()deprecated calls - Fixed
get_product_index_name()method call - Fixed product_db.php using
get_option()directly
📝 Technical Details:
- New
VERIFY_PRclass cho auto verify & sync - Enhanced
LOG_PRclass với database logging - Cron job chạy mỗi giờ:
es_cron_auto_verify_sync - Log categories: verify_sync, verify_delete_extra, verify_fix_failed
Version 1.4.1 (05/12/2025)
✨ New Features:
- 🎯 Product Configuration Section: Thêm phần cấu hình riêng cho Product
- Tag-based input cho Indexable Post Statuses (publish, draft, pending, private...)
- Auto-suggestion cho các WordPress post statuses phổ biến
- Section tự động hiện/ẩn theo checkbox Product
- 📦 CONFIG_DB Class: Class mới quản lý config tập trung
get_option_keys()- Lấy danh sách option keys của plugindelete_all_options()- Xóa tất cả options khi uninstallget/update_indexable_statuses()- Quản lý indexable statusesget/set/release_indexing_lock()- Quản lý indexing lock
- 🗑️ Uninstall Cleanup: Tự động xóa tất cả plugin options khi uninstall
es_setting,es_indexable_statuseses_logs_per_page,es_indexing_lock,es_stop_indexing
🔧 Improvements:
- Product count now respects configured indexable statuses
- Moved
get_indexable_statuses()to PRODUCT_DB class - Added i18n strings for Product Configuration section
🐛 Bug Fixes:
- Fixed product count mismatch - chỉ đếm products với configured statuses
- Fixed missing cleanup of plugin options on uninstall
Version 1.4.0 (01/12/2025)
✨ New Features:
- 📝 Log Admin Page Redesign: Complete UI overhaul matching Product Admin style
- 🗑️ Delete All Logs Confirmation: Custom showConfirm() popup dialog
🐛 Bug Fixes:
- Fixed HTML nested forms error in Log Admin
- Fixed Log Admin page not loading CSS/FontAwesome icons
- Fixed count_product() total calculation
Version 1.3.9 (28/11/2025)
🔥 Major Changes:
- 🚀 OPTIMIZED HOOKS: Giảm từ 32 hooks xuống 16 hooks không trùng lặp
- Loại bỏ các hooks redundant (edit_post, post_updated, woocommerce_new_product, etc.)
- Tăng hiệu năng, giảm overhead khi save product
- ✨ ES DELETE HANDLING: Xử lý xóa sản phẩm khỏi Elasticsearch
action='deleted'→ Xóa document khỏi ES (product bị xóa vĩnh viễn)action='trashed'→ Re-index với post_status='trash'- Priority system: 'deleted' action không bị override
- 🔄 AUTO RESET STUCK: Tự động reset cả index stuck và delete stuck
- Status 5 → Status 0 sau 5 phút
- Status 7 → Status 6 sau 5 phút
New Features:
- ✅
process_realtime_delete()- Xử lý xóa realtime qua ES API - ✅
mark_products_for_delete_batch()- Queue mode delete - ✅
mark_products_processing_delete()- Realtime mode delete - ✅ Separate tracking cho index vs delete operations
- ✅ Added
product_shipping_classtaxonomy support
Improvements:
- 🎯 Simplified
es_sync_product()function với Vietnamese comments - 🎯 Trigger merging khi cùng 1 product trigger nhiều hooks trong 1 request
- 🎯 Better logging với trigger count display
- 🎯 Variation stock changes now sync parent product
Status Codes Updated:
| Code | Name | Description |
|---|---|---|
| 0 | pending_index | Chờ đánh index |
| 1 | index_success | Index thành công |
| 2 | index_failed | Index thất bại |
| 5 | processing_index | Đang xử lý index |
| 6 | pending_delete | Chờ xóa khỏi ES |
| 7 | processing_delete | Đang xử lý xóa |
| 8 | delete_success | Xóa thành công |
| 9 | delete_failed | Xóa thất bại |
Version 1.3.8 (20/11/2025)
Improvements:
- 🚀 Simplified Analyzer Language - now defaults to English (removed from UI)
- 🌐 Full multilingual support for CLI commands using
__()function - 🎯 Removed
--max-batchesparameter from CLI (simplified usage) - 🔄 Added
--continuousflag for CLI: single batch for cron, continuous for manual - 🐛 Fixed continuous flag logic check in batch processing loop
- 📝 Updated CLI messages: "Logging to database" → "Saving logs to database"
- 🔧 Improved CLI command workflow for better cron job compatibility
Breaking Changes:
- ⚠️ Analyzer Language setting removed from Config UI (hardcoded to 'english')
- ⚠️
--max-batchesCLI parameter removed (use--continuousflag instead)
Version 1.3.7 (19/11/2025)
New Features:
- ✨ Console Monitor with real-time logs
- ✨ 18 WordPress hooks for auto-sync
- ✨ WP-CLI commands support
- ✨ Advanced mapping settings (shards, replicas, field limit)
- ✨ Analyzer language configuration
- ✨ Reindex all/failed products buttons
- ✨ Force clear lock mechanism
- ✨ Batch sync at shutdown hook
Improvements:
- 🚀 Optimized database queries
- 🚀 Better bulk indexing performance
- 🚀 Lock mechanism to prevent conflicts
- 🚀 Auto-reset stuck products (5 min)
- 🚀 Auto-cleanup old logs (7 days)
Bug Fixes:
- 🐛 Fixed nested mapping for taxonomies
- 🐛 Fixed memory issues with large batches
- 🐛 Fixed lock not releasing on error
- 🐛 Fixed console logs encoding
Developer:
- 🔧 Added 10+ action/filter hooks
- 🔧 Comprehensive hook documentation
- 🔧 Example code snippets
Version 1.3.6 (14/10/2025)
Initial release
HỖ TRỢ
📚 Tài Liệu
Đọc kỹ tài liệu hướng dẫn này và các file trong thư mục doc/.
📧 Email Support
Gửi yêu cầu hỗ trợ qua email:
aboyit@hotmail.com
🌐 Website
Truy cập website:
webnew.info.vn
📄 LICENSE
GPL-2.0 License
Copyright (C) 2025 Aboyit
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.