← Blog

Claude API WordPress Plugin Development Guide

2026-11-24 · 5 min read · SubToAPI Team

Building a WordPress plugin that talks to Claude means solving three problems at once: keeping your API key off the client, making server-to-server requests from PHP without blocking page loads, and giving editors a usable admin interface. This guide walks through the actual plugin architecture — file structure, request handling, streaming in a PHP environment, and settings storage — so you can ship something that works in production, not just in a local sandbox.

If you're searching for "claude api wordpress plugin development" you're probably trying to add AI-generated content, a chat widget, or an automated editorial assistant to a WordPress site. The core challenge isn't calling an LLM — it's doing it safely inside WordPress's request lifecycle, where PHP execution time, nonces, and plugin update cycles all matter more than in a typical Node or Python backend.

Plugin Architecture Basics

A Claude-powered WordPress plugin typically needs four pieces:

File structure for a minimal plugin:

claude-content-assistant/
├── claude-content-assistant.php
├── includes/
│   ├── class-settings.php
│   ├── class-rest-api.php
│   └── class-api-client.php
└── assets/
    └── admin.js

The key architectural decision: your PHP backend calls the Claude API, not the browser. This keeps your key server-side and lets you apply WordPress capability checks (current_user_can('edit_posts')) before any model call happens.

Storing the API Key Safely

Use the WordPress Options API, and consider encrypting the value or at minimum restricting it to manage_options capability:

register_setting('claude_assistant_options', 'claude_api_key', [
    'sanitize_callback' => 'sanitize_text_field',
]);

Never expose the key in wp_localize_script() or inline JS. If you need the browser to trigger a generation, route it through your own REST endpoint, which then makes the outbound call server-side.

Building the REST Proxy Endpoint

add_action('rest_api_init', function () {
    register_rest_route('claude-assistant/v1', '/generate', [
        'methods'  => 'POST',
        'callback' => 'claude_assistant_generate',
        'permission_callback' => function () {
            return current_user_can('edit_posts');
        },
    ]);
});

function claude_assistant_generate(WP_REST_Request $request) {
    $prompt = sanitize_textarea_field($request->get_param('prompt'));
    $api_key = get_option('claude_api_key');

    $response = wp_remote_post('https://api.subtoapi.app/v1/messages', [
        'timeout' => 30,
        'headers' => [
            'Authorization' => 'Bearer ' . $api_key,
            'Content-Type'  => 'application/json',
        ],
        'body' => wp_json_encode([
            'model' => 'claude-sonnet-4',
            'max_tokens' => 1024,
            'messages' => [
                ['role' => 'user', 'content' => $prompt],
            ],
        ]),
    ]);

    if (is_wp_error($response)) {
        return new WP_Error('claude_request_failed', $response->get_error_message(), ['status' => 500]);
    }

    $body = json_decode(wp_remote_retrieve_body($response), true);
    return rest_ensure_response($body);
}

Using a plain HTTPS endpoint like this (rather than Anthropic's native SDK, which assumes a Node/Python runtime) is often simpler in PHP because wp_remote_post() already handles timeouts, redirects, and WordPress's HTTP API filters. This is also where a service like SubToAPI fits naturally into WordPress plugin development: it exposes Claude as a standard HTTPS JSON API with sub_live_... application keys, so your plugin's PHP code only needs wp_remote_post() and a bearer token — no separate SDK dependency to bundle or maintain inside the plugin's vendor/ directory. Check the quickstart for the exact request shape.

Handling WordPress's Execution Time Limits

PHP's default max_execution_time (often 30–60 seconds) is a real constraint for longer Claude completions. Three practical options:

  1. Increase the timeout for this specific request only, using set_time_limit(90) inside the callback.
  2. Move generation to WP Cron or Action Scheduler for non-interactive tasks (e.g., nightly content summaries), storing results as post meta.
  3. Use streaming so the browser gets tokens as they arrive instead of waiting for the full response — see below.

Streaming Responses in a PHP Plugin

True server-sent streaming inside WordPress is awkward because wp_remote_post() buffers the full response by default. For a responsive chat-style UI, the more reliable pattern is: have your JS call your REST endpoint, which proxies to a streaming-capable backend, and use curl_setopt(CURLOPT_WRITEFUNCTION) directly instead of the WP HTTP API when you need token-by-token output:

$ch = curl_init('https://api.subtoapi.app/v1/messages');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $api_key,
    'Content-Type: application/json',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    'model' => 'claude-sonnet-4',
    'stream' => true,
    'messages' => $messages,
]));
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $chunk) {
    echo $chunk;
    flush();
    return strlen($chunk);
});
curl_exec($ch);

This bypasses WordPress's HTTP API abstraction intentionally — it's one of the few cases where raw cURL in a plugin is the right call. Full event format details are in the streaming docs.

Giving Claude Access to WordPress Data

If your plugin needs Claude to act on post content — summarizing drafts, suggesting tags, rewriting excerpts — define tools that map to WordPress functions like wp_update_post() or wp_set_post_tags(), and let the model call them with structured arguments. This is standard tool-use, documented at /docs/tools, and it's the pattern that turns a plugin from "generate text into a textarea" into "assistant that safely edits the post via capability-checked WordPress functions."

Testing and Shipping

Before submitting to the WordPress.org plugin directory or distributing privately:

For teams building multiple WordPress-integrated tools, a shared account with per-key usage tracking (available on Team and Scale plans) makes it easier to see which plugin or client site is driving API usage without digging through server logs. You can test the full request/response flow with a free trial at signup.

Final Thoughts

Claude API WordPress plugin development is less about the model and more about respecting WordPress's execution model: capability checks, nonces, timeout limits, and the Options API. Get those right first, then layer on streaming or tool use once the basic request/response proxy is solid. See /docs/messages for the full request schema reference.

FAQ

Can I call the Claude API directly from JavaScript in a WordPress plugin? No — doing so exposes your API key in the browser. Always proxy requests through a WordPress REST route or admin-ajax handler so the key stays server-side in PHP.

Why does my plugin's Claude request time out on shared hosting? Shared hosts often cap PHP execution time well below what a long completion needs. Use set_time_limit() for the specific request, or move long-running generations to WP Cron / Action Scheduler.

Do I need the official Anthropic SDK to build a WordPress plugin? No. Since WordPress plugins run in PHP, calling a plain HTTPS JSON endpoint with wp_remote_post() or cURL is simpler than bundling an SDK built for Node or Python runtimes.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →