Integrating ChatGPT & LLM APIs Into WordPress: A Practical Guide
WordPress clients increasingly want AI features baked into their site — a smart search, an on-site assistant, automated content tagging. The integration pattern is fairly consistent across these use cases.
The Architecture
LLM API keys should never live in client-side JavaScript. The correct pattern:
- Front-end (a custom block, widget, or Elementor element) sends a request to a WordPress REST API endpoint
- A custom plugin, registered via
register_rest_route, receives the request server-side - The plugin calls the LLM API using a securely stored API key
- The response is sanitized and returned to the front end
A Basic Example
add_action('rest_api_init', function () {
register_rest_route('site/v1', '/ai-assist', [
'methods' => 'POST',
'callback' => 'handle_ai_assist_request',
'permission_callback' => '__return_true',
]);
});
function handle_ai_assist_request($request) {
$prompt = sanitize_text_field($request->get_param('prompt'));
$api_key = get_option('site_ai_api_key');
$response = wp_remote_post('https://api.example.com/v1/messages', [
'headers' => [
'x-api-key' => $api_key,
'content-type' => 'application/json',
],
'body' => json_encode([
'model' => 'default-model',
'max_tokens' => 512,
'messages' => [['role' => 'user', 'content' => $prompt]],
]),
]);
return rest_ensure_response(json_decode(wp_remote_retrieve_body($response)));
}
Things That Actually Matter in Production
- Rate limiting — Without it, a single bad actor can run up your API bill fast
- Caching repeated queries — Many AI features answer near-identical questions repeatedly
- Graceful failure — The site should work fine if the AI feature is down, not break the page
- Cost monitoring — LLM API costs scale with usage in a way flat-rate plugins don't
Where This Fits Into a Plugin
This kind of integration is usually built as a small, focused custom plugin rather than a general-purpose one — the same principle covered in Custom WordPress Plugin Development.
The Bigger Picture
AI features are a tool, not a strategy. The businesses getting real value are the ones that identified a specific, repetitive problem first — see AI Automation for Small Businesses: Where to Actually Start.
Let's Build Something
I'm Shahid Latif — a WordPress developer and AI automation specialist, and a Top Rated Plus freelancer on Upwork. Learn more about me or get in touch.