---
title: Using the WordPress AI Client
description: Add AI features to a WordPress plugin or theme without calling the AI API directly.
url: https://developers.wpengine.com/docs/ai/api/wordpress-ai-client/
image: https://developers.wpengine.com/og/docs/ai/api/wordpress-ai-client.png
---

# Using the WordPress AI Client

If you’re building a WordPress plugin or theme, you may not need to call the AI API directly. WordPress 7.0 includes a built-in [AI Client](https://make.wordpress.org/core/2026/03/24/introducing-the-ai-client-in-wordpress-7-0/) with a fluent PHP API for text, image, and speech generation.

The WP Engine AI Connector plugin registers a `wpengine` provider for the AI Client. Your code never handles an API key, and you don’t manage authentication, retries, or provider routing yourself.

## Prerequisites

1. Install and activate the [WP Engine AI Connector](https://wp-product-info.wpesvc.net/v1/plugins/wpe-ai-connector?download) and [WP Engine AI](https://wp-product-info.wpesvc.net/v1/plugins/wpe-hub?download) plugins.
2. Go to **Settings → Connectors → WP Engine AI Connector** and connect the site to a WP Engine account.
3. Run WordPress 7.0 or later. The AI Client is part of WordPress core, so your plugin or theme calls it directly. You don’t need to install anything else.

> **No API key in code**
>
> After you connect the connector to a WP Engine account, the connector authenticates every request automatically. You don’t set an `Authorization` header.

## Generate text and images

Generate text with the fluent builder. The AI Client picks a suitable model from the registered providers, sends the request through the connector, and returns the generated text.

```php
<?php
declare( strict_types = 1 );


$summary = wp_ai_client_prompt( 'Summarize the speed of light in one sentence.' )
    ->using_system_instruction( 'You are concise.' )
    ->generate_text();


if ( is_wp_error( $summary ) ) {
    // Log the error and fall back to a non-AI code path.
    return;
}
```

`generate_text()` returns a `string` on success and a `WP_Error` on failure. `wp_ai_client_prompt()` converts every AI Client exception into a `WP_Error`, so always check the result with `is_wp_error()`.

For the full result object, use `generate_text_result()` instead. It includes token usage, the model that generated the response, and the finish reason. The `wpengine` provider returns one candidate per request, so request a single result instead of several with `generate_texts()`.

To control cost, latency, or capability, pin specific models. List them in order of preference. The AI Client uses the first one the connector exposes:

```php
$summary = wp_ai_client_prompt( 'Summarize the speed of light in one sentence.' )
    ->using_provider( 'wpengine' )
    ->using_model_preference( 'google/gemini-3.8-flash', 'anthropic/claude-haiku-5-5' )
    ->generate_text();
```

Without a preference, the connector uses the model selected on its settings screen. The default is Claude Sonnet 5.5. If that model can’t handle the prompt, the connector falls back to the newest Claude Sonnet, then Haiku, then Fable, then Gemini Flash.

Web search works on Claude and on Gemini 3 and newer. Gemini can only block domains, so a web search that sets allowed domains needs a Claude model. Structured output (a JSON schema) needs Gemini. The AI API lists text as the only response format for Claude models.

To reorder the fallback chain, use the `wpe/ai/connector/fallback_models` filter:

```php
add_filter(
    'wpe/ai/connector/fallback_models',
    function ( array $models ): array {
        // Try Haiku before Sonnet.
        usort(
            $models,
            fn ( string $a, string $b ): int =>
                (int) str_contains( $b, 'claude-haiku-' ) <=> (int) str_contains( $a, 'claude-haiku-' )
        );


        return $models;
    }
);
```

The filter orders models but can’t exclude them. Any model the connector offers that isn’t in the chain still comes after the chain. Removing a model from the chain only moves it down the list.

The connector stores the order with the cached model list. A change takes effect after you save the connector settings, the plugin is updated, or the 24-hour cache expires.

The connector reports itself as unavailable in these cases:

- The site isn’t connected.
- The current request isn’t allowed to use the connection. See [Control who can make requests](https://developers.wpengine.com/docs/ai/api/wordpress-ai-client/#control-who-can-make-requests).
- For about a minute after WP Engine AI fails to list its models.

Check availability before you show an AI feature, so you can hide the feature instead of showing an error. WordPress core doesn’t wrap this check, so call the bundled software development kit (SDK) class directly:

```php
use WordPress\AiClient\AiClient;


if ( ! AiClient::isConfigured( 'wpengine' ) ) {
    // Show an admin notice or fall back to a non-AI code path.
    return;
}
```

To generate an image, replace `generate_text()` with `generate_image()`. It returns a `WordPress\AiClient\Files\DTO\File` with inline, base64-encoded image data. Decode the data to save the image to the uploads directory:

```php
$image = wp_ai_client_prompt( 'A pixel-art lighthouse at sunset' )
    ->using_provider( 'wpengine' )
    ->generate_image();


if ( is_wp_error( $image ) ) {
    return;
}


// $image->getMimeType() reports the format, e.g. image/png.
$upload = wp_upload_bits(
    'lighthouse.png',
    null,
    base64_decode( $image->getBase64Data() )
);
```

## Control who can make requests

The connector attaches the site’s credentials to a request only when the request runs as one of the following:

- A logged-in user with the `edit_posts` capability (Contributor and above)
- WP-CLI
- WP-Cron

For any other request, `AiClient::isConfigured( 'wpengine' )` returns `false`, and WordPress skips the connector when it picks a model. This includes a request made while WordPress renders a page for an anonymous visitor. A call pinned to the connector with `using_provider( 'wpengine' )` returns a `WP_Error`, and the connector never attaches the site’s credentials to it.

To allow other requests, filter `wpe_ai_connector_authorize_request`. The filter also decides whether the connector is offered at all. For that check, the filter receives a `GET` request to `v1/models`, so a filter that inspects the request URL must allow that request too.

```php
add_filter(
    'wpe_ai_connector_authorize_request',
    function ( bool $authorized ): bool {
        return $authorized || my_plugin_can_use_ai();
    }
);
```

> **Every authorized request uses the site’s credits**
>
> Authorizing anonymous visitors lets anyone who can reach that code path spend the site’s AI credits. Put your own rate limiting or abuse protection in front of any public-facing AI feature.

## Restrict which plugins use the connector

A site can also restrict which plugins use the connector. The [WordPress AI plugin](https://wordpress.org/plugins/ai/) has an optional Connector Approval experiment, which is off by default.

When a site administrator turns on the experiment, calls from a plugin that hasn’t been approved to use the `wpengine` connector return a `WP_Error`. The error has the code `prompt_network_error` and a message saying the connector has not been approved for that plugin. The blocked plugin then appears as a pending request under **Tools → Connector Approvals**, where an administrator can approve it.

## Call the AI API for other features

The AI Client is a provider-agnostic content-generation layer, not a full AI API client. It works with any registered AI provider, so it exposes only generation primitives that apply across providers. It has no methods for:

- Token counting, transcription, image alt-text, content summarization, or taxonomy suggestion
- Usage analytics or credit balance
- Site registration or connection management (handled by the WP Engine AI and WP Engine AI Connector plugins, not the AI Client)
- Agents, sessions, or knowledge base collections
- The Model Context Protocol (MCP) transport used by external clients such as Claude Code

For any of those, call the [AI API](https://developers.wpengine.com/docs/ai/api/) directly.

> **Where to learn more**
>
> The AI Client also supports speech and text-to-speech generation through the same fluent API. For the full builder API and provider model, see [Introducing the AI Client in WordPress 7.0](https://make.wordpress.org/core/2026/03/24/introducing-the-ai-client-in-wordpress-7-0/). That announcement post, not this page, is the authoritative reference for the AI Client’s methods.

---

> #### Going beyond the AI Client
>
> - [Getting started — call the API directly](https://developers.wpengine.com/docs/ai/api/getting-started/)
> - [Authentication — the key the gateway expects](https://developers.wpengine.com/docs/ai/api/authentication/)

## Was this helpful?

Thanks for the feedback!

```json
{"@context":"https://schema.org","@graph":[{"@type":"WebSite","@id":"https://developers.wpengine.com/#website","name":"WP Engine Product Documentation","url":"https://developers.wpengine.com/","description":"Resources for developing, deploying, and scaling on WP Engine.","inLanguage":"en-US","keywords":["API documentation","product documentation","headless WordPress","managed WordPress hosting"],"publisher":{"@id":"https://wpengine.com/#organization"}}]}
```
