REST API & Integrations

Calling an AI API from WordPress Without Wrecking the Site

Server-side calls, key handling, queued background jobs, cost controls and the editorial guardrails that keep generated text from going live unreviewed.

Calling an AI API from WordPress — original abstract editorial artwork
In this article

Adding an AI feature to a WordPress site has become easy to prototype: a few lines of code send a prompt to a model provider's API and print the response. The prototype usually works in a demo and fails in production, because it makes a slow, paid request during a page load, exposes or mishandles the API key and publishes whatever the model returns.

This guide covers the parts that make an AI integration safe to run on a real business site: where the call happens, where the key lives, how long requests are queued, how costs are capped and how a person stays in control of what visitors see. The principles apply whichever provider you use.

Never from the browser: the key belongs on the server

Any API key that reaches the browser can be copied by anyone who opens the developer tools, and then used to run up charges on your account. That includes keys embedded in JavaScript, passed in a data attribute or returned by an unauthenticated AJAX endpoint. Calls to a model provider must start on your server.

In WordPress, that means a custom REST route or an admin action that receives the user's request, checks their permissions and a nonce, builds the prompt on the server and calls the provider with wp_remote_post. The browser only ever talks to your site. This also gives you one place to validate input, apply limits and log usage.

Storing secrets outside the database and outside the repository

Plugins often store API keys in the wp_options table, which means every database backup, staging copy and export contains the key in plain text. Keys committed to a Git repository are worse, because they stay in its history even after removal.

Prefer an environment variable or a constant defined in wp-config.php, with wp-config.php itself excluded from version control and readable only by the web server user. Use a separate key for each environment so a leaked staging key cannot be used against production, and set the provider's own usage limits on each key. If you must accept a key through an admin screen, restrict the screen to administrators and never echo the full key back into the page.

Long calls belong in a queue, not in a page request

Model responses can take several seconds, and longer for large outputs. A page that waits for one feels broken, and if many visitors trigger generation at once, PHP workers fill up and the whole site slows down. Anything that is not an interactive chat should run in the background.

Action Scheduler, which ships with WooCommerce and can be used as a standalone library, is a solid choice for queued jobs in WordPress. The request creates a job and returns immediately; a background runner calls the provider, stores the result in post meta or a custom table and marks the job complete. The admin screen polls or refreshes to show the result. WP-Cron alone is less reliable on low-traffic sites, because it only runs when someone visits, so pair it with a real server cron if you depend on it.

  • Create a job with the input and the user who requested it
  • Run the API call in a background worker with a timeout
  • Store the result and the token usage with the job
  • Notify or refresh the editor's screen when it is ready

Caching responses, and the prompt hash that makes it possible

Many AI features are asked the same thing repeatedly: a summary of the same article, alt text for the same image, a translation of the same paragraph. Paying for each request is wasteful. Build a cache key from a hash of everything that affects the output, including the model name, the prompt template version, the settings and the input text, and store the result against it.

Before calling the provider, look the hash up. If a result exists and is still valid, return it immediately. When you change the prompt template, change its version so old results are not reused for the new prompt. Transients work for short-lived results; for anything you want to keep, store it with the post so it is backed up and easy to review.

Cost controls: token ceilings, per-user limits, a hard monthly cap

Costs grow through three routes: long inputs, long outputs and too many requests. Limit each one. Trim input to what the task needs, set a maximum output length on every request and rate-limit each user and each IP address for any feature visitors can reach.

Record the token usage the provider returns with each job, and keep a running monthly total. When the total reaches a threshold, alert the site owner; when it reaches a hard cap, stop accepting new jobs and show a polite message. Set a spending limit in the provider's dashboard as well, so a bug in your own accounting cannot produce an unlimited bill.

Failure handling when the provider is slow or down

Model providers have outages, rate limits and slow periods like any other API. Set explicit timeouts on wp_remote_post, treat 429 and 5xx responses as retryable with an increasing delay, and stop after a few attempts. Mark the job as failed with a readable reason so an editor knows what happened.

Design the feature so the site still works without it. If summaries cannot be generated, show the article without one. If a chatbot is unavailable, show the contact form. Never let a failed AI call block checkout, enquiries or publishing.

Editorial review before anything generated reaches a visitor

Language models produce fluent text that can be wrong, outdated or inappropriate for your brand. On a business site that is a reputational and sometimes legal risk, especially for product claims, prices, health information or anything that sounds like advice. Treat generated text as a draft.

Save AI output as a draft, a pending revision or a suggestion field that an editor must accept, and record who approved it. For customer-facing chat, limit the assistant to approved content, make clear that it is automated and offer a route to a person. Guard against prompt injection by never giving the model authority to take actions on its own and by treating its output as untrusted input. The third-party API integration guide and the custom REST endpoints guide cover the WordPress side, and the AI API integrations service explains how I scope these features.

Frequently asked questions

How do I connect an AI API to WordPress?

Create a server-side endpoint or admin action that checks permissions, builds the prompt and calls the provider with the WordPress HTTP API. Run slow generation as a background job, store the result and show it to an editor for review.

Where should the API key be stored?

In an environment variable or a constant in wp-config.php that is excluded from version control, with a separate key and spending limit for each environment. Avoid storing it in the options table, in JavaScript or in the code repository.

How do I stop AI API costs running away?

Cap input and output length, rate-limit users, cache repeated requests by a hash of the prompt and settings, track token usage per job and enforce a monthly cap in both your code and the provider's dashboard.

Should AI-generated content be published automatically?

For a business site, no. Save generated text as a draft or suggestion and have a person review it before publication, because models can produce confident but incorrect statements about products, prices or policies.

Topics

  • WordPress AI API integration
  • OpenAI API WordPress
  • add AI to WordPress site
  • WordPress background job API call
Share

Sources and further reading