AIForum.

Building a WordPress Plugin That Calls an AI API: Security, Caching, and Cost Controls

On this page

THE SHORT ANSWER

A deployable WordPress AI plugin is not just an API call — it is a server-side proxy plus four supporting systems: a cache, a rate limit, a cost log, and safe credential storage. This guide walks through each component, with illustrative code, verification checks, and the tradeoffs that decide how you configure them.
Quick facts

Building a WordPress plugin that calls an AI API is easy. Making one you can leave running on a live site is the harder engineering problem. The request itself is a few lines of code; what separates a demo from a deployable plugin is the scaffolding around it — a server-side proxy that keeps the API key out of the browser, a cache that stops you paying twice for the same answer, a rate limit that stops one user or bot from draining the budget, and a log that tells you what you actually spent.

This guide is for a technically curious beginner or intermediate WordPress developer. It describes a production-oriented pattern drawn from two published WordPress AI integration guides, cited inline. The code below is illustrative — it has not been tested by this publication — and should be adapted to your own environment rather than copied verbatim.

The gap between a demo and a deployable plugin

A WordPress-focused integration guide states the problem directly: calling an API and printing the result is a demo, and the distance between that demo and something you can leave running on a client’s live site — caching, error handling, cost control, and a settings page that stores the key safely — is the entire job (The WP Clan). That framing doubles as a checklist, because each item maps to a concrete component you have to build.

A second write-up supplies the architecture: frontend (block or admin screen) → WordPress REST endpoint on the server → AI provider, with caching at the WordPress layer, rate limiting per user and per site, background jobs for long-running tasks, and audit logs stored in a custom table with PII minimization (AI Guy in LA). Both guides converge on the same shape: the browser never talks to the AI provider directly.

Prerequisites

  • WordPress 6.4 or newer and PHP 8.1 or newer, the baseline named in the production-pattern guide.
  • A persistent object cache (Redis or Memcached) is recommended. Without one, transients fall back to the database and cache reads become slower queries.
  • A job runner such as Action Scheduler for anything that would otherwise time out a normal request.
  • A way to keep the API key outside the plugin directory — wp-config.php constants or environment variables.

Step 1: Route everything through a server-side proxy

The first security decision is architectural. Any key shipped to the browser — in JavaScript, in a block’s front-end bundle, or in a REST response — is public. The pattern both sources describe is a WordPress REST endpoint that receives a request from an authenticated admin screen or block, calls the provider server-side, and returns only the model’s output.

Register the route with a permission_callback that checks capability and, ideally, a nonce. If the endpoint is meant for logged-in editors, require current_user_can( 'edit_posts' ) or a more specific capability rather than leaving it open to anonymous requests.

Step 2: Store the credential where the plugin cannot leak it

The production-pattern guide recommends environment configuration for secrets — wp-config.php or environment variables — rather than storing the key in the database, where it can surface in a backup, a migration, or a settings export.

// wp-config.php (illustrative)
define( 'AI_PROVIDER_API_KEY', getenv( 'AI_PROVIDER_API_KEY' ) );

Avoid a settings page that echoes the stored key back into an HTML form. If you must offer an admin UI, show a masked placeholder and only overwrite the stored value when a new key is submitted.

Step 3: Wrap the HTTP call with real error handling

For plugins, direct HTTP is often simpler than pulling in an SDK, because it avoids Composer dependency management inside the plugin directory (The WP Clan). In WordPress that means wp_remote_post() with the provider’s required headers.

// Illustrative only — not editor-tested.
class AI_Proxy_Client {
    private $api_key;
    private $model    = 'claude-sonnet-4-20250514';
    private $endpoint = 'https://api.anthropic.com/v1/messages';

    public function __construct( $api_key ) {
        $this->api_key = $api_key;
    }

    public function send( $prompt, $system = '', $max_tokens = 1024 ) {
        $body = array(
            'model'      => $this->model,
            'max_tokens' => $max_tokens,
            'messages'   => array(
                array( 'role' => 'user', 'content' => $prompt ),
            ),
        );

        if ( $system ) {
            $body['system'] = $system;
        }

        $response = wp_remote_post( $this->endpoint, array(
            'headers' => array(
                'Content-Type'      => 'application/json',
                'x-api-key'         => $this->api_key,
                'anthropic-version' => '2023-06-01',
            ),
            'body'    => wp_json_encode( $body ),
            'timeout' => 30,
        ) );

        if ( is_wp_error( $response ) ) {
            return new WP_Error( 'ai_http', $response->get_error_message() );
        }

        $status = wp_remote_retrieve_response_code( $response );
        $data   = json_decode( wp_remote_retrieve_body( $response ), true );

        if ( 200 !== $status ) {
            $message = isset( $data['error']['message'] ) ? $data['error']['message'] : 'Unknown API error';
            return new WP_Error( 'ai_api', $message, array( 'status' => $status ) );
        }

        return isset( $data['content'][0]['text'] ) ? $data['content'][0]['text'] : '';
    }
}

Three details matter more than they look. The timeout prevents a stalled request from holding a PHP worker. The is_wp_error() check catches transport failures that never produce an HTTP status. And returning a WP_Error instead of an empty string lets calling code distinguish “the model returned nothing” from “the request failed.”

Step 4: Cache by a hash of the whole request

Caching is the single largest cost lever, because identical requests are common — regenerating a summary, re-rendering a block, or a user refreshing a page. Both guides place the cache at the WordPress layer using transients or the object cache.

// Illustrative only.
$cache_key = 'ai_resp_' . hash( 'sha256', $prompt . '|' . $model . '|' . $max_tokens );
$cached    = get_transient( $cache_key );

if ( false !== $cached ) {
    return $cached;
}

$result = $client->send( $prompt );

if ( ! is_wp_error( $result ) ) {
    set_transient( $cache_key, $result, 12 * HOUR_IN_SECONDS );
}

Include every parameter that changes the output — model name, max tokens, temperature, system prompt — in the hash. A cache keyed only on the user prompt will serve a short answer where a long one was requested. Choose the TTL from how volatile the underlying content is, and delete the transient when the source post is saved, so an edited page does not keep showing a stale summary.

Step 5: Rate limit per user and per site

Rate limiting protects both your bill and the provider’s quota. The production-pattern guide describes limiting per user and per site to prevent abuse. A transient counter is enough for a single-server site:

// Illustrative only: 20 requests per user per hour.
$limit_key = 'ai_rl_' . get_current_user_id() . '_' . gmdate( 'YmdH' );
$count     = (int) get_transient( $limit_key );

if ( $count >= 20 ) {
    return new WP_Error( 'ai_rate_limited', 'Hourly AI request limit reached.', array( 'status' => 429 ) );
}

set_transient( $limit_key, $count + 1, HOUR_IN_SECONDS );

Return HTTP 429 so the client can back off, and log the event. Combine a per-user limit with a site-wide ceiling: a single compromised account should not be able to consume the entire monthly budget before anyone notices.

Step 6: Control cost before it controls you

Cost control has four practical levers, in rough order of impact:

  1. Cache aggressively. A cache hit costs nothing at the provider.
  2. Cap output with max_tokens. Output tokens are the part of the bill you control most directly; a summarization task rarely needs a 4,000-token ceiling.
  3. Match the model to the task. Use the cheapest model that reliably passes your own evaluation for the job, and reserve larger models for tasks that demonstrably need them.
  4. Track usage per feature. Log input and output token counts so you can attribute spend to a specific block, form, or admin tool.

Do not estimate prices from memory. Provider pricing and model lineups change; check the current published rates, record the date you checked them, then multiply by your logged token counts. If you cannot verify a price, present the calculation as a formula with the rate left as a variable rather than inventing a figure.

Step 7: Log for observability, and minimize what you store

The production-pattern guide stores audit records in a custom table with columns for user ID, route, a request hash, input tokens, output tokens, duration in milliseconds, status code, error text, and a timestamp. The request hash is the important design choice: it lets you correlate duplicate requests and cache hits without storing the raw prompt.

Prompts frequently contain customer data, unpublished drafts, or personal information. Store a hash and a length, not the text, unless you have a specific debugging need and a retention policy that covers it. If you do store prompt text, say so in your privacy policy and give it an expiry date.

Verifying the setup

Four observable checks confirm the pattern is working:

  1. Send the same request twice from the admin screen. The second response should return quickly and produce no new audit row with a non-zero token count.
  2. Exceed the rate limit deliberately. The endpoint should return a 429 with your error message, not a generic 500.
  3. Inspect the browser’s network tab. No request to the AI provider’s domain should appear — only requests to your own REST route.
  4. Query the audit table. Token counts and durations should be populated, and req_hash values should repeat for identical inputs.

Common errors and what they usually mean

  • 401 or “invalid x-api-key”: the key is missing, truncated, or being read from a constant that is not defined in the current environment.
  • 400 with a model error: the model identifier is wrong or retired. Model names change; treat them as configuration, not as hard-coded constants.
  • 429 from the provider: this is the provider’s rate limit, not yours. Add retry with backoff rather than retrying immediately.
  • Empty string returned: the response parsed but content[0].text was absent — often a safety stop or an unexpected response shape. Log the raw status and body, not just the parsed text.
  • Request times out at the web server: the task is too long for a synchronous request. Move it to Action Scheduler and return a job ID.

Tradeoffs and limitations

Caching introduces staleness: a TTL that is too long serves outdated text, and one that is too short barely saves money. Rate limits can block legitimate power users, so make the ceiling configurable and log rejections. Transients without a persistent object cache are stored in the database, which means cache reads are queries — acceptable at low volume, less so at high volume. And a proxy endpoint is still an endpoint: it needs capability checks, nonce verification, and input validation, because model output is untrusted text that may end up rendered in an admin screen.

None of this removes the need for human review where output is published or used in a decision. The pattern described here is about plumbing, not about whether the generated text is correct.

Next step

Pick one feature — a post summary, a product description draft, a classification step in a form — and implement the four components in order: proxy, cache, rate limit, log. Instrument it before you scale it, and let the token log tell you whether the feature is worth keeping. If you hit a specific error, or find a caching tradeoff that behaves differently on your host, share the environment details and the observed result in the community so others can reproduce it.

FAQ

Can the browser call the AI provider directly to save a round trip?

No. Any key delivered to the browser is effectively public. Route the request through a WordPress REST endpoint that holds the credential server-side and returns only the model output.

How long should AI responses be cached?

There is no universal TTL. Base it on how volatile the source content is, include model and parameters in the cache key, and delete the transient when the underlying post is saved.

Do I need Redis or Memcached for this?

Not strictly. A persistent object cache is recommended, but transients fall back to the database when none is available — workable at low volume, slower at high volume.

How do I stop one user from running up the bill?

Combine a per-user rate limit with a site-wide ceiling, cap output with max_tokens, and log input and output token counts so spend can be attributed to a specific feature.

References

  1. https://thewpclan.com/wordpress-plugins-claude-api/
  2. https://aiguyinla.com/blog/a-production-grade-pattern-for-ai-endpoints-in-wordpress-secure-proxy-caching-rate-limits-observability

Related terms

Transient
A WordPress key/value store with an expiry time; used here both to cache AI responses and to count rate-limit hits.
Object cache
A persistent in-memory cache such as Redis or Memcached. When present, transients are stored there instead of in the database.
max_tokens
The request parameter that caps how many tokens the model may generate in its reply.
Request hash
A SHA-256 digest of the request parameters, logged in place of the raw prompt to limit stored personal data.
Proxy endpoint
A WordPress REST route that receives a request from the browser and performs the provider call server-side.
Action Scheduler
A background job runner used in WordPress to process tasks that would otherwise time out a normal request.

Leave a Reply

Your email address will not be published. Required fields are marked *