Giới thiệu
Slash /ai không được tích hợp sẵn vì nếu bật theo mặc định sẽ dẫn đến việc plugin tự đốt ví người dùng. Plugin cho phép tự mở rộng bằng cách đăng ký slash command tự động qua 3 đoạn code: PHP filter cho query, filter cho gợi ý, và JS handler.
Bước 1: Khai báo slash /ai và gợi ý
add_filter('init_plugin_suite_live_search_commands', function ($commands) {
$commands['ai'] = __('Ask AI (OpenAI)', 'init-live-search');
return $commands;
});
Bước 2: Tùy biến truy vấn vì slash /ai không phải để query post
add_filter('init_plugin_suite_live_search_query_args', function ($args, $mode, $request) {
if ($request->get_param('term') === '/ai') {
$args['post__in'] = [0]; // chặn query
}
return $args;
}, 10, 3);
Bước 3: Gọi OpenAI API từ JS
Trong JS, khi bắt sự kiện ils:search-started, ta có thể gọi endpoint API cá nhân để lấy câu trả lời từ OpenAI:
window.addEventListener('ils:search-started', (e) => {
const term = (e.detail?.term || '').trim();
if (!term.startsWith('/ai ')) return;
const prompt = term.replace('/ai', '').trim();
if (!prompt) return;
window.ilsHelpers.showLoading();
fetch('/wp-json/init/v1/ai?prompt=' + encodeURIComponent(prompt))
.then(res => res.json())
.then(data => {
const html = `<div class="ils-ai-answer">${data.answer || 'No response'}</div>`;
window.ilsHelpers.setRawContent(html);
})
.catch(() => {
window.ilsHelpers.showMessage('Error contacting AI');
});
});
Bước 4: Viết endpoint /wp-json/init/v1/ai trong theme/plugin
add_action('rest_api_init', function () {
register_rest_route('init/v1', '/ai', [
'methods' => 'GET',
'callback' => function ($request) {
$key = get_option('init_ai_key');
if (!$key) return rest_ensure_response(['answer' => 'AI disabled.']);
$prompt = sanitize_text_field($request->get_param('prompt'));
$res = wp_remote_post('https://api.openai.com/v1/chat/completions', [
'headers' => [
'Authorization' => 'Bearer ' . $key,
'Content-Type' => 'application/json',
],
'body' => json_encode([
'model' => 'gpt-3.5-turbo',
'messages' => [
['role' => 'system', 'content' => 'You are an AI assistant for a WordPress website.'],
['role' => 'user', 'content' => $prompt],
],
]),
]);
$json = json_decode(wp_remote_retrieve_body($res), true);
return ['answer' => $json['choices'][0]['message']['content'] ?? 'No reply'];
},
]);
});
Lưu ý bảo mật khi sử dụng slash /ai
Endpoint /wp-json/init/v1/ai là REST API mở, nếu bạn không giới hạn quyền truy cập, bất kỳ ai cũng có thể gửi prompt và sử dụng API Key của bạn — kể cả khi không vào trang web.
Để tránh bị lạm dụng và mất chi phí không mong muốn, bạn nên:
- Chỉ cho phép người dùng đã đăng nhập gọi API (dùng
is_user_logged_in()). - Giới hạn độ dài prompt (ví dụ tối đa 300 ký tự).
- Giới hạn tần suất mỗi IP bằng cách lưu transient (ví dụ: chỉ 1 request mỗi 10 giây).
- (Tuỳ chọn) Thêm token bí mật nếu muốn mở API cho bên ngoài.
Không nên để endpoint mở hoàn toàn mà không có giới hạn — vì chỉ cần một đoạn script spam là bạn sẽ mất tiền nhanh chóng.
Kết luận
Chỉ cần 3 đoạn code và 1 endpoint REST API, bạn đã có thể biến Init Live Search thành trợ lý ChatGPT mini. Plugin không tích hợp sẵn tính năng này, nhưng luôn sẵn sàng để bạn tùy biến. Hãy nhớ: tính năng này tính phí theo API của OpenAI, và plugin không chịu trách nhiệm nếu bạn phát sinh chi phí không mong muốn.
Bình luận