### Quick Start: Define AI SDK Tools
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/ai-sdk.mdx
Set up a WordPress client and define generic tools for content searching, reading, and writing using the AI SDK. This example demonstrates how to initialize the client and create tools for content operations.
```typescript
import { WordPressClient } from 'fluent-wp-client';
import {
getContentCollectionTool,
getContentTool,
saveContentTool,
} from 'fluent-wp-client/ai-sdk';
const wp = new WordPressClient({
baseUrl: 'https://example.com',
auth: { username: 'admin', password: 'xxxx xxxx xxxx xxxx' },
});
await wp.explore();
const tools = {
searchPosts: getContentCollectionTool(wp, {
contentType: 'posts',
description: 'Search published blog posts.',
fixedArgs: { status: 'publish', fields: ['id', 'slug', 'title', 'excerpt', 'link'] },
}),
readContent: getContentTool(wp),
writePost: saveContentTool(wp, {
contentType: 'posts',
fixedInput: { status: 'draft' },
}),
};
```
--------------------------------
### Development Setup and Commands
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/README.md
Commands for managing the local WordPress development environment and running tests. This includes starting and stopping the WordPress Docker container.
```bash
# Start the local WordPress environment
npm run wp:start
# Run the integration test suite
npm test
# Stop the environment
npm run wp:stop
```
--------------------------------
### Install fluent-wp-client
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/index.mdx
Install the package using npm.
```bash
npm install fluent-wp-client
```
--------------------------------
### Install Turndown
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/examples/content-to-markdown.mdx
Install the turndown library and its types for converting HTML to Markdown.
```bash
npm install turndown @types/turndown
```
--------------------------------
### Quick Start: Use AI SDK Tools with an Agent
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/ai-sdk.mdx
Integrate the defined WordPress tools into an AI agent for generating text. This example shows how to pass the tools to the `generateText` function from the AI SDK.
```typescript
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';
const { text } = await generateText({
model: openai('gpt-4o'),
tools,
prompt: 'Find the latest 3 posts about TypeScript and summarize them.',
});
```
--------------------------------
### Plugin Documentation Frontmatter Example
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/AGENTS.md
Example frontmatter for plugin documentation using Astro Starlight, specifying title, short_title, and description.
```mdx
---
title: Plugin Documentation
short_title: Documentation
description: Guidance for writing plugin docs with structured front matter metadata.
---
```
--------------------------------
### Describe-first Agent Example
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/examples/describe-first-agent.mdx
This example sets up an AI agent that uses WordPress tools for content introspection, reading, and writing. It first loads and caches the WordPress catalog, then defines tools for describing resources, reading content, and writing content. A system prompt instructs the agent to always describe unfamiliar content types before interacting with them.
```typescript
import {
generateText
} from 'ai';
import {
openai
} from '@ai-sdk/openai';
import {
WordPressClient
} from 'fluent-wp-client';
import {
describeResourceTool,
getContentTool,
saveContentTool,
} from 'fluent-wp-client/ai-sdk';
const wp = new WordPressClient({
baseUrl: 'https://blog.example.com',
auth: {
username: 'editor',
password: process.env.WP_APP_PASSWORD!,
},
});
// Seed the catalog once. Every describe call below is served from memory.
await wp.explore();
const tools = {
describeResource: describeResourceTool(wp),
readContent: getContentTool(wp),
writeContent: saveContentTool(wp, { contentType: 'posts' }),
};
const system = `
You are an editorial assistant for a WordPress site.
Before reading or writing any content type for the first time, ALWAYS call
"describeResource" with the matching kind and name (e.g. { kind: 'content',
name: 'posts' }). Use its schema to decide which fields to request on reads
and which fields to set on writes.
"writeContent" covers both creating and updating posts. Call it without "id"
to create a new post, or with "id" to update an existing one. Only use it
after you have described "posts" in the current session.
`
.trim();
const { text } = await generateText({
model: openai('gpt-4o'),
tools,
maxSteps: 8,
system,
prompt: 'Draft a short announcement post introducing our new product launch, then publish it.',
});
```
--------------------------------
### Model-Facing Content Examples
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/ai-sdk.mdx
Examples of how to structure requests for content tools, including collection searches and single-item reads or mutations.
```json
{ contentType: 'posts', search: 'release notes', perPage: 5 }
```
```json
{ contentType: 'pages', slug: 'about' }
```
```json
{ contentType: 'books', input: { title: 'New Book', status: 'draft' } }
```
```json
{ contentType: 'books', id: 42, input: { status: 'publish' } }
```
--------------------------------
### FileTree Component Example
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/AGENTS.md
Demonstrates the usage of the Astro Starlight FileTree component to visualize folder structure.
```mdx
import { FileTree } from '@astrojs/starlight/components';
- src/
- ...
```
--------------------------------
### Install Dependencies for AI SDK
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/ai-sdk.mdx
Install the necessary packages for using the AI SDK with Fluent WordPress Client. The `ai` package is only required when importing from `fluent-wp-client/ai-sdk`.
```bash
npm install fluent-wp-client ai
```
--------------------------------
### Setup WordPress Client with Blocks
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/gutenberg-content.mdx
Initialize the WordPress client and enhance it with block functionality. Ensure you have the correct base URL and authentication credentials.
```typescript
import { WordPressClient } from 'fluent-wp-client';
import { withBlocks } from 'fluent-wp-client/blocks';
const wp = new WordPressClient({
baseUrl: 'https://example.com',
auth: { username: 'admin', password: 'app-password' },
});
const wpBlocks = withBlocks(wp);
```
--------------------------------
### Quick Start: Initialize and Fetch Data
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/README.md
Initialize the WordPress client and demonstrate fetching a list of posts, a single post, and creating a draft post. Requires authentication for creation.
```typescript
import { WordPressClient } from 'fluent-wp-client';
const wp = new WordPressClient({
baseUrl: 'https://your-wordpress-site.com',
});
const posts = wp.content('posts');
// Read a list of posts
const recentPosts = await posts.list({ perPage: 10 });
// First-class resources use the same fluent style
const comments = await wp.comments().list({ post: 42 });
// Read a single post
const post = await posts.item('hello-world');
// Create a draft post (requires auth)
const draft = await posts.create({ title: 'Hello', status: 'draft' });
```
--------------------------------
### MDX Frontmatter Example
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/AGENTS.md
Example of frontmatter configuration for MDX files in Astro Starlight, including title, description, and sidebar options.
```mdx
---
title: Configuration
description: Configure webhook behavior using methods, filters, and the registry.
sidebar:
order: 2
---
```
--------------------------------
### AI SDK Example with Runtime Schema Discovery
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/schema-discovery.mdx
Use runtime schema discovery with the AI SDK to allow models to adapt to the current site's capabilities before executing mutations. This example validates AI-generated input against a dynamically generated schema.
```typescript
import { generateObject } from 'ai';
import { openai } from '@ai-sdk/openai';
import { zodFromJsonSchema } from 'fluent-wp-client/zod';
const desc = await wp.content('posts').describe();
const createSchema = zodFromJsonSchema(desc.schemas.create!);
const { object } = await generateObject({
model: openai('gpt-4o-mini'),
schema: createSchema!,
prompt: 'Draft a short post announcing our April product update.',
});
await wp.content('posts').create(object);
```
--------------------------------
### CRUD Walkthrough: Posts and Pages
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/usage.mdx
Provides examples for performing Create, Update, and Delete operations on posts and pages using the client.
```APIDOC
## CRUD walkthrough
### Posts and pages
```ts
const posts = wp.content('posts');
const created = await posts.create({ title: 'My post', status: 'draft' });
await posts.update(created.id, { title: 'Updated', status: 'publish' });
await posts.delete(created.id, { force: true });
```
```
--------------------------------
### Users and Settings
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/usage.mdx
Demonstrates how to retrieve the current user's information and get or update site settings.
```APIDOC
### Users and settings
```ts
const me = await wp.users().me();
const settings = await wp.settings().get();
await wp.settings().update({ title: 'New Title' });
```
```
--------------------------------
### Initialize WordPress Client with Gutenberg Blocks Add-on
Source: https://context7.com/juvojustin/fluent-wp-client/llms.txt
Wrap a standard `WordPressClient` instance with the `withBlocks` function to enable Gutenberg-aware methods. Ensure the necessary subpackage and peer dependencies are installed.
```typescript
import { WordPressClient } from 'fluent-wp-client';
import { withBlocks, parseWordPressBlocks, serializeWordPressBlocks, validateWordPressBlocks } from 'fluent-wp-client/blocks';
const wp = new WordPressClient({
baseUrl: 'https://example.com',
auth: { username: 'admin', password: 'app-password' },
});
const wpBlocks = withBlocks(wp);
```
--------------------------------
### CRUD Walkthrough: Comments
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/usage.mdx
Provides examples for creating, updating, and deleting comments on posts.
```APIDOC
### Comments
```ts
const comment = await wp.comments().create({ post: 42, content: 'Nice!', status: 'approve' });
await wp.comments().update(comment.id, { content: 'Updated.' });
await wp.comments().delete(comment.id, { force: true });
```
```
--------------------------------
### Get Settings with Custom Fetch
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/ai-sdk.mdx
Provide a custom `fetch` callback to `getSettingsTool` for cached reads of the singleton settings. The callback receives no arguments.
```typescript
const getSettings = getSettingsTool(adminWp, {
fetch: async () => settingsCache.get(),
});
```
--------------------------------
### WordPress Client Authentication Examples
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/README.md
Configure authentication for the WordPress client using different strategies: Basic Auth with application passwords, JWT tokens, or browser-based cookie authentication with nonces.
```typescript
// Basic auth (WordPress application passwords)
const wp = new WordPressClient({
baseUrl: 'https://example.com',
auth: { username: 'admin', password: 'app-password' },
});
// JWT auth
const wp = new WordPressClient({
baseUrl: 'https://example.com',
auth: { token: 'jwt-token' },
});
// Cookie + nonce (browser sessions)
const wp = new WordPressClient({
baseUrl: 'https://example.com',
auth: { nonce: window.wpApiSettings.nonce, credentials: 'include' },
});
```
--------------------------------
### Inline Catalog Restoration
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/examples/dynamic-schema-exploration.mdx
Chain the `useCatalog()` method directly after client instantiation for a more concise setup.
```typescript
const wp = new WordPressClient({ baseUrl: 'https://example.com', auth: { ... } })
.useCatalog(stored);
```
--------------------------------
### Describe a resource
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/schema-discovery.mdx
Call `.describe()` on any resource client to get its JSON Schemas for item, collection, create, and update operations.
```APIDOC
## Describe a resource
### Description
Call `.describe()` on any resource client to get its JSON Schemas.
### Method
```ts
const desc = await wp.content('books').describe();
desc.schemas.item // single item response shape
desc.schemas.collection // collection response shape
desc.schemas.create // accepted fields for create
desc.schemas.update // accepted fields for update (no required fields)
```
### Endpoint
```ts
await wp.terms('categories').describe();
await wp.media().describe();
await wp.users().describe();
await wp.comments().describe();
await wp.settings().describe();
await wp.ability('my-plugin/send-notification').describe();
```
```
--------------------------------
### Get Full Resource Description
Source: https://context7.com/juvojustin/fluent-wp-client/llms.txt
Fetches the complete JSON Schema for a resource, including schemas for item, collection, create, and update operations. Write schemas require an authenticated client.
```typescript
// Full description for a resource
const desc = await wp.content('books').describe();
console.log(desc.schemas.item); // response shape
console.log(desc.schemas.create); // accepted fields for create
console.log(desc.schemas.update); // accepted fields for update
```
--------------------------------
### Resource Filtering for Generation
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/cli.mdx
Limit artifact generation to specific resources by using the `--include` and `--exclude` flags with resource slugs or REST bases. This example generates artifacts only for `books` and `genre`.
```bash
npx fluent-wp-client schemas \
--url https://example.com \
--include posts,books,genre \
--exclude posts
```
--------------------------------
### Initialize Settings Tools
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/ai-sdk.mdx
Use `getSettingsTool` and `updateSettingsTool` to manage WordPress settings. These tools operate on a singleton endpoint.
```typescript
const tools = {
getSettings: getSettingsTool(adminWp),
updateSettings: updateSettingsTool(adminWp),
};
```
--------------------------------
### AI SDK Error Envelope Example
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/ai-sdk.mdx
Example of the structured error envelope returned by AI SDK tools for runtime validation failures or HTTP-level failures.
```typescript
{
ok: false,
error: {
kind: 'invalid_request',
message: "describeResourceTool(): 'posts' is not available for kind 'content'. Allowed values: books.",
},
}
```
--------------------------------
### Create a WordPress Client Instance
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/index.mdx
Instantiate the WordPressClient with your site's base URL.
```typescript
import { WordPressClient } from 'fluent-wp-client';
const wp = new WordPressClient({
baseUrl: 'https://your-wordpress-site.com',
});
```
--------------------------------
### Get Current User Information
Source: https://context7.com/juvojustin/fluent-wp-client/llms.txt
Use the `.me()` helper to fetch details about the currently authenticated user.
```typescript
const me = await wp.users().me();
```
--------------------------------
### Describe All Resource Types
Source: https://context7.com/juvojustin/fluent-wp-client/llms.txt
Demonstrates fetching schema descriptions for various resource types including terms, media, users, comments, settings, and specific abilities. This showcases the versatility of the describe() method.
```typescript
// Works for all resource types
await wp.terms('categories').describe();
await wp.media().describe();
await wp.users().describe();
await wp.comments().describe();
await wp.settings().describe();
await wp.ability('my-plugin/send-notification').describe();
```
--------------------------------
### settings()
Source: https://context7.com/juvojustin/fluent-wp-client/llms.txt
Provides access to site settings as a singleton resource, using `.get()` and `.update()` methods.
```APIDOC
## settings()
### Description
Returns a `SettingsResourceClient`. Unlike other resources, settings is a singleton that uses `.get()` and `.update()` instead of `.list()` and `.item()`.
### Methods
- `get()`: Reads the current site settings.
- `update(options)`: Updates site settings (requires admin capabilities).
- `describe()`: Discovers and returns the available schema for settings operations.
### Request Example (Get Settings)
```ts
const settings = await wp.settings().get();
console.log(settings.title, settings.description);
```
### Request Example (Update Settings)
```ts
await wp.settings().update({
title: 'My WordPress Site',
description: 'Just another site'
});
```
### Request Example (Describe)
```ts
const desc = await wp.settings().describe();
console.log(desc.schemas.item);
```
```
--------------------------------
### Custom Taxonomy Reads and CRUD
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/custom-endpoints.mdx
Provides examples for listing, creating, updating, and deleting custom taxonomy terms.
```APIDOC
## Custom Taxonomy Reads and CRUD
Assume `rest_base: 'genre'`.
```ts
const genres = wp.terms('genre');
// List terms with pagination
const list = await genres.list({ perPage: 100 });
// List all terms
const allGenres = await genres.listAll();
// Create a new term
const created = await genres.create({ name: 'Science Fiction' });
// Update an existing term
await genres.update(created.id, { name: 'Sci-Fi' });
// Delete a term
await genres.delete(created.id, { force: true });
```
```
--------------------------------
### Unified post-like resource API (recommended)
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/usage.mdx
Demonstrates the recommended unified API for interacting with post-like resources and terms.
```APIDOC
## Unified post-like resource API (recommended)
```ts
const posts = wp.content('posts');
const recentPosts = await posts.list({ perPage: 10 });
const post = await posts.item('hello-world');
const books = wp.content('books');
const allBooks = await books.listAll();
const genres = await wp.terms('genre').list({ perPage: 100 });
```
```
--------------------------------
### Model-Facing Inputs for Schema Introspection
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/ai-sdk.mdx
Examples of model-facing inputs for `describeResourceTool`, specifying the `kind` and `name` of the resource or ability to describe.
```typescript
{ kind: 'content', name: 'books' }
{ kind: 'term', name: 'categories' }
{ kind: 'resource', name: 'users' }
{ kind: 'ability', name: 'acme/send-email' }
```
--------------------------------
### Create AI SDK Tools for WordPress
Source: https://context7.com/juvojustin/fluent-wp-client/llms.txt
Composably create AI SDK tools for various WordPress entities. Tools can be configured with fixed resource types or left dynamic for runtime model selection. Ensure the WordPress client is initialized and its catalog is populated before creating tools.
```typescript
import { WordPressClient } from 'fluent-wp-client';
import {
getContentCollectionTool,
getContentTool,
saveContentTool,
deleteContentTool,
getTermCollectionTool,
saveTermTool,
getResourceCollectionTool,
saveResourceTool,
executeRunAbilityTool,
createAbilityTools,
getBlocksTool,
setBlocksTool,
getSettingsTool,
updateSettingsTool,
describeResourceTool,
} from 'fluent-wp-client/ai-sdk';
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';
const wp = new WordPressClient({
baseUrl: 'https://example.com',
auth: { username: 'editor', password: 'app-password' },
});
await wp.explore(); // populate catalog for enum schemas
const tools = {
// Fixed content type — model doesn't see contentType in input
searchPosts: getContentCollectionTool(wp, {
contentType: 'posts',
description: 'Search published blog posts.',
fixedArgs: { status: 'publish', fields: ['id', 'slug', 'title', 'excerpt'] },
}),
// Dynamic content type — model supplies contentType at runtime
readAnyContent: getContentTool(wp),
// saveContentTool routes to create (no id) or update (id present) automatically
writePost: saveContentTool(wp, {
contentType: 'posts',
fixedInput: { status: 'draft' },
}),
// Term tools
listGenres: getTermCollectionTool(wp, { taxonomyType: 'genre' }),
// Ability tools — one tool per discovered ability
...createAbilityTools(wp, {
include: ['acme/get-stats', 'acme/send-email'],
needsApproval: (_name, ability) => ability.annotations?.destructive === true,
}),
// Blocks
getPostBlocks: getBlocksTool(wp, { contentType: 'posts' }),
setPostBlocks: setBlocksTool(wp, { contentType: 'posts' }),
// Settings
readSettings: getSettingsTool(wp),
// Schema introspection tool for the model
describeResource: describeResourceTool(wp, {
include: { content: ['posts', 'books'], term: ['categories', 'genre'] },
}),
};
const { text } = await generateText({
model: openai('gpt-4o'),
tools,
prompt: 'Find the latest 3 posts about TypeScript and summarize them.',
});
```
--------------------------------
### Get Raw and Rendered Content
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/gutenberg-content.mdx
Retrieve both raw block markup and rendered HTML for a post. Requires edit capabilities.
```typescript
const content = await wp.content('posts').item('hello-world').getContent();
content.rendered // HTML
content.raw // block markup
```
--------------------------------
### Populate Client Cache with Catalog
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/ai-sdk.mdx
Use `wp.explore()` or `wp.useCatalog()` to populate the client cache. This enables catalog-aware schemas, which dynamically adjust tool behavior based on the connected WordPress instance.
```typescript
const catalog = await wp.explore();
wp.useCatalog(catalog);
const writeBook = saveContentTool(wp, {
contentType: 'books',
});
```
--------------------------------
### CRUD Walkthrough: Terms
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/usage.mdx
Demonstrates how to create, update, and delete terms (e.g., categories, tags) using the client.
```APIDOC
### Terms
```ts
const cat = await wp.terms('categories').create({ name: 'News' });
await wp.terms('categories').update(cat.id, { name: 'Company News' });
await wp.terms('categories').delete(cat.id, { force: true });
```
```
--------------------------------
### Initialize WordPressClient
Source: https://context7.com/juvojustin/fluent-wp-client/llms.txt
Instantiate the WordPressClient with various authentication methods like Basic, JWT, or cookie+nonce. The `onRequest` callback can be used for features like rate limiting.
```typescript
import { WordPressClient } from 'fluent-wp-client';
// Public read-only
const wp = new WordPressClient({ baseUrl: 'https://example.com' });
// Basic auth (application passwords)
const wpAdmin = new WordPressClient({
baseUrl: 'https://example.com',
auth: { username: 'admin', password: 'xxxx xxxx xxxx xxxx' },
});
// JWT auth
const wpJwt = new WordPressClient({
baseUrl: 'https://example.com',
auth: { token: 'your-jwt-token' },
});
// Cookie + nonce (browser sessions)
const wpBrowser = new WordPressClient({
baseUrl: 'https://example.com',
auth: { nonce: window.wpApiSettings.nonce, credentials: 'include' },
});
// Rate limiting via onRequest callback
const wpThrottled = new WordPressClient({
baseUrl: 'https://example.com',
auth: { username: 'admin', password: 'xxxx xxxx xxxx xxxx' },
onRequest: async (_url, _init) => {
await new Promise(resolve => setTimeout(resolve, 100));
},
});
```
--------------------------------
### Get a specific schema variant
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/schema-discovery.mdx
Use `getJsonSchema()` when you only need a specific schema variant (e.g., 'create' or 'update') from a fluent resource client.
```APIDOC
## Get a specific schema variant
### Description
Use `getJsonSchema()` when you only need one schema variant from a fluent resource client.
### Method
```ts
const createSchema = await wp.content('books').getJsonSchema('create');
const updateSchema = await wp.content('books').getJsonSchema('update');
```
```
--------------------------------
### Get Specific Schema Variant Directly
Source: https://context7.com/juvojustin/fluent-wp-client/llms.txt
Retrieves a specific JSON Schema variant (e.g., 'create' or 'update') for a resource directly. This is useful when only a particular schema is needed.
```typescript
// Get one variant directly
const createSchema = await wp.content('books').getJsonSchema('create');
const updateSchema = await wp.content('books').getJsonSchema('update');
```
--------------------------------
### Fluent Ability Execution with Reusable Handles
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/abilities.mdx
Obtain a reusable ability handle using `client.ability(name)` for fluent interaction, including `run`, `get`, and `delete` methods.
```typescript
const processComplex = wp
.ability<
{ name: string; settings: { theme: string } },
{ processed: boolean; echo: { name: string } }
>('test/process-complex')
;
const result = await processComplex.run({
name: 'demo',
settings: { theme: 'dark' },
});
```
--------------------------------
### List and Upload Media
Source: https://context7.com/juvojustin/fluent-wp-client/llms.txt
Use the media client to list existing media items and upload new files. Ensure you have a Blob or File object for uploads.
```typescript
const images = await wp.media().list({ perPage: 20 });
```
```typescript
const uploaded = await wp.media().upload({
file: imageBlob,
// Blob or File
filename: 'cover.jpg',
mimeType: 'image/jpeg',
title: 'Cover image',
alt_text: 'Book cover',
});
```
--------------------------------
### JWT Authentication for WordPress Client
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/auth.mdx
Set up JWT authentication for the WordPress client. This requires the 'JWT Authentication for WP REST API' plugin to be installed and active on your WordPress site.
```typescript
const wp = new WordPressClient({
baseUrl: 'https://example.com',
auth: { token: 'jwt-token' },
});
```
--------------------------------
### WordPress Abilities API
Source: https://context7.com/juvojustin/fluent-wp-client/llms.txt
Provides a fluent builder for the WordPress Abilities API at `/wp-json/wp-abilities/v1`. Supports listing, describing, and executing registered abilities with GET, POST, and DELETE semantics.
```APIDOC
## ability() — WordPress Abilities API
Provides a fluent builder for the WordPress Abilities API at `/wp-json/wp-abilities/v1`. Supports listing, describing, and executing registered abilities with GET, POST, and DELETE semantics.
### Direct execution helpers
```ts
// Direct execution helpers
const siteTitle = await wp.executeGetAbility<{ title: string }>('test/get-site-title');
const updated = await wp.executeRunAbility<{ previous: string; current: string }>(
'test/update-option',
{ value: 'hello' },
);
const deleted = await wp.executeDeleteAbility<{ deleted: boolean }>('test/delete-option');
```
### Fluent builder for reusable ability handles
```ts
// Fluent builder for reusable ability handles
const processComplex = wp.ability<
{ name: string; settings: { theme: string } },
{ processed: boolean; echo: { name: string } }
>('test/process-complex');
const result = await processComplex.run({ name: 'demo', settings: { theme: 'dark' } });
const definition = await processComplex.getDefinition();
```
### Validate input against the live schema before executing
```ts
// Validate input against the live schema before executing
import { z } from 'zod';
const desc = await wp.ability('test/process-complex').describe();
const inputSchema = z.fromJSONSchema(desc.schemas.input!);
const validatedInput = inputSchema.parse({ name: 'demo', settings: { theme: 'dark' } });
const validated = await wp.ability('test/process-complex').run(validatedInput);
```
### Metadata
```ts
// Metadata
const abilities = await wp.getAbilities();
const category = await wp.getAbilityCategory('test');
```
```
--------------------------------
### Initialize Gutenberg Block Tools
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/ai-sdk.mdx
Use `getBlocksTool` and `setBlocksTool` to interact with Gutenberg blocks. Requires edit-level authentication and specifies the content type.
```typescript
const getBlocks = getBlocksTool(adminWp, {
contentType: 'posts',
});
const setBlocks = setBlocksTool(adminWp, {
contentType: 'posts',
});
```
--------------------------------
### Create Resource Collection and Save Tools
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/ai-sdk.mdx
Use `getResourceCollectionTool` for listing resources and `saveResourceTool` for creating or updating resources. `saveResourceTool` supports comments and users, creating when `id` is absent and updating when `id` is provided. Media uploads require direct use of `client.media().upload()`.
```typescript
const listUsers = getResourceCollectionTool(adminWp, {
resourceType: 'users',
});
const writeUser = saveResourceTool(adminWp, {
resourceType: 'users',
});
const deleteComment = deleteResourceTool(adminWp, {
resourceType: 'comments',
});
```
--------------------------------
### WordPress abilities
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/usage.mdx
Demonstrates how to execute WordPress abilities for custom actions and data retrieval.
```APIDOC
## Abilities
```ts
const siteTitle = await wp.executeGetAbility<{ title: string }>('test/get-site-title');
const result = await wp
.ability<{ name: string }, { processed: boolean }>('test/process-complex')
.run({ name: 'demo' });
```
```
--------------------------------
### CRUD Walkthrough: Media
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/usage.mdx
Shows how to upload and delete media items, such as images, using the client.
```APIDOC
### Media
```ts
const media = await wp.media().upload({
file: imageBlob, filename: 'cover.jpg', mimeType: 'image/jpeg',
title: 'Cover', alt_text: 'Book cover',
});
await wp.media().delete(media.id, { force: true });
```
```
--------------------------------
### Fluent first-class resource clients
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/usage.mdx
Illustrates the usage of first-class resource clients for media, users, comments, and settings.
```APIDOC
## First-class resources
```ts
const media = await wp.media().list({ perPage: 20 });
const me = await wp.users().me();
const comments = await wp.comments().list({ post: 42 });
const settings = await wp.settings().get();
```
```
--------------------------------
### Parse and Retrieve Gutenberg Blocks from a Post
Source: https://context7.com/juvojustin/fluent-wp-client/llms.txt
Access post content using `wpBlocks.content('posts').item()` to retrieve blocks. The `get` method can optionally validate blocks against provided schemas.
```typescript
const postQuery = wpBlocks.content('posts').item('hello-world');
const blocks = await postQuery.blocks().get({ schemas: blockSchemas, validate: true });
// blocks = [{ blockName: 'core/paragraph', attrs: {}, innerHTML: '
...
', innerBlocks: [], innerContent: [...] }]
```
--------------------------------
### Read Site Settings
Source: https://context7.com/juvojustin/fluent-wp-client/llms.txt
Retrieve the current site settings using the `.get()` method. The output includes title and description.
```typescript
const settings = await wp.settings().get();
console.log(settings.title, settings.description);
```
--------------------------------
### Extend Built-in Zod Schemas
Source: https://context7.com/juvojustin/fluent-wp-client/llms.txt
Demonstrates extending built-in Zod schemas provided by the client library with custom fields, such as ACF fields. This allows for more specific validation tailored to your WordPress setup.
```typescript
// Extend built-in Zod schemas
import { postSchema } from 'fluent-wp-client/zod';
const extendedPostSchema = postSchema.extend({
acf: z.object({ acf_subtitle: z.string().optional() }).optional(),
});
const post = extendedPostSchema.parse(await wp.content('posts').item('hello-world'));
```
--------------------------------
### WordPressClient Constructor
Source: https://context7.com/juvojustin/fluent-wp-client/llms.txt
Instantiates a new WordPressClient. Configuration options include baseUrl, authentication methods (Basic, JWT, Cookie+nonce), and request handling callbacks.
```APIDOC
## WordPressClient Constructor
### Description
Creates a new WordPress API client. Accepts `baseUrl`, `auth`, `authHeader`, `authHeaders`, `cookies`, `credentials`, `fetch`, and `onRequest` in the config. All subsequent API calls flow through this instance.
### Usage Examples
```ts
import { WordPressClient } from 'fluent-wp-client';
// Public read-only
const wp = new WordPressClient({ baseUrl: 'https://example.com' });
// Basic auth (application passwords)
const wpAdmin = new WordPressClient({
baseUrl: 'https://example.com',
auth: { username: 'admin', password: 'xxxx xxxx xxxx xxxx' },
});
// JWT auth
const wpJwt = new WordPressClient({
baseUrl: 'https://example.com',
auth: { token: 'your-jwt-token' },
});
// Cookie + nonce (browser sessions)
const wpBrowser = new WordPressClient({
baseUrl: 'https://example.com',
auth: { nonce: window.wpApiSettings.nonce, credentials: 'include' },
});
// Rate limiting via onRequest callback
const wpThrottled = new WordPressClient({
baseUrl: 'https://example.com',
auth: { username: 'admin', password: 'xxxx xxxx xxxx xxxx' },
onRequest: async (_url, _init) => {
await new Promise(resolve => setTimeout(resolve, 100));
},
});
```
```
--------------------------------
### Describe Settings Schema
Source: https://context7.com/juvojustin/fluent-wp-client/llms.txt
Discover the schema for site settings, useful for understanding the structure of settings data.
```typescript
const desc = await wp.settings().describe();
console.log(desc.schemas.item);
```
--------------------------------
### Flexible Collection Filtering
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/README.md
Filter collections using typed core filters like `search`, `include`, and `slug`. This example demonstrates filtering posts by search term and IDs, and books by IDs and title search.
```typescript
const posts = await wp.content('posts').list({
search: 'hello world',
include: [4, 8],
titleSearch: 'Hello',
});
const books = await wp.content('books').list({
include: [164, 165],
titleSearch: 'Test Book',
});
```
--------------------------------
### Get Resource Metadata for Agent Tool Building
Source: https://context7.com/juvojustin/fluent-wp-client/llms.txt
Retrieves metadata like query parameters, readable fields, and writable fields for a resource. This information is valuable for building agent tools or dynamic client interfaces.
```typescript
// Resource metadata for agent tool building
const queryParams = await wp.content('posts').getQueryParams();
const readableFields = await wp.content('posts').getReadableFields();
const writableFields = await wp.content('posts').getWritableFields();
```
--------------------------------
### Import WordPress Discovery Types
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/schema-discovery.mdx
Import core types for WordPress API discovery, including catalog, options, schema, and resource descriptions.
```typescript
import type {
WordPressDiscoveryCatalog,
WordPressDiscoveryOptions,
WordPressJsonSchema,
WordPressResourceDescription,
WordPressAbilityDescription,
} from 'fluent-wp-client';
```
--------------------------------
### Get Catalog Selectors
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/agent-integration.mdx
Retrieve catalog selectors to build framework-native discriminated unions, select inputs, or define AI tool schemas. These selectors are derived from the client's cached catalog or by running discovery.
```typescript
const selectors = await wp.getCatalogSelectors();
// selectors.contentType -> { type: 'string', enum: ['posts', 'pages', ...] }
// selectors.taxonomyType -> { type: 'string', enum: ['categories', 'tags', ...] }
// selectors.resourceType -> { type: 'string', enum: ['media', 'comments', ...] }
// selectors.abilityName -> { type: 'string', enum: ['namespace/action', ...] }
```
--------------------------------
### Create and Use Auth Resolvers
Source: https://context7.com/juvojustin/fluent-wp-client/llms.txt
Demonstrates creating a typed auth resolver for request contexts and using it with WordPressClient. Useful for SSR or environments where request details are available.
```typescript
import {
WordPressClient,
createAuthResolver,
resolveWordPressAuth,
createBasicAuthHeader,
createJwtAuthHeader,
} from 'fluent-wp-client';
// Per-request signed headers (HMAC / OAuth-style)
const wpSigned = new WordPressClient({
baseUrl: 'https://example.com',
authHeaders: ({ method, url, body }) => ({
Authorization: createSignedAuthHeader({ method, url: url.toString(), body }),
'X-Signature-Timestamp': new Date().toISOString(),
}),
});
// Request-scoped auth resolver for SSR handlers
const requestAuth = createAuthResolver((request: Request) => {
const jwt = request.headers.get('cookie')?.match(/wp_jwt=([^;]+)/)?.[1];
if (jwt) return { token: decodeURIComponent(jwt) };
if (process.env.WP_APP_PASSWORD) return { username: 'admin', password: process.env.WP_APP_PASSWORD };
return null;
});
// Next.js App Router example
export async function GET(request: Request, { params }: { params: { slug: string } }) {
const auth = await resolveWordPressAuth(requestAuth, request);
const wp = new WordPressClient({ baseUrl: process.env.WORDPRESS_BASE_URL!, auth });
return Response.json(await wp.content('posts').item(params.slug));
}
// JWT login and validation
const wpPublic = new WordPressClient({ baseUrl: 'https://example.com' });
const tokenResponse = await wpPublic.loginWithJwt({ username: 'admin', password: 'secret' });
// tokenResponse.token — use this as { token: '...' } auth
const validation = await wpPublic.validateJwtToken(tokenResponse.token);
// Low-level header helpers
const basicHeader = createBasicAuthHeader({ username: 'admin', password: 'app-pass' });
const jwtHeader = createJwtAuthHeader({ token: 'jwt-token' });
```
--------------------------------
### Restrict Describe Tool Access
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/examples/describe-first-agent.mdx
This example shows how to limit the scope of the `describeResourceTool` by providing an `include` option. This allows you to specify which content types, terms, or resources the AI model is permitted to describe, enhancing security and control.
```typescript
const describe = describeResourceTool(wp, {
include: {
// Only expose two content types and one resource.
content: ['posts', 'books'],
resource: ['users'],
// `term` and `ability` are omitted → removed from the tool's input schema.
},
});
```
--------------------------------
### Use the WordPress Client for API Operations
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/index.mdx
Perform various operations like listing posts, getting items with embedded relations, creating content, and accessing first-class resources. Use helper functions for extracting embedded author and term data.
```typescript
import { WordPressClient, getEmbeddedAuthor, getEmbeddedTerms } from 'fluent-wp-client';
const wp = new WordPressClient({
baseUrl: 'https://your-wordpress-site.com',
});
// List posts
const posts = await wp.content('posts').list({ perPage: 10 });
// Get a single item with embedded relations
const book = await wp.content('books').item('my-book', { embed: true });
const author = getEmbeddedAuthor(book);
const genres = getEmbeddedTerms(book, 'genre');
// Create (requires auth)
const draft = await wp.content('posts').create({ title: 'Hello', status: 'draft' });
// First-class resources
const comments = await wp.comments().list({ post: 42 });
const me = await wp.users().me();
```
--------------------------------
### First-class resource methods
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/usage.mdx
Overview of methods available for first-class resources like media, users, comments, and settings.
```APIDOC
### First-class resources
| Resource | Extras |
| --- | --- |
| `media()` | `.upload()`, `.getImageUrl()` |
| `users()` | `.me()` |
| `comments()` | — |
| `settings()` | `.get()`, `.update()`, `.describe()` (singleton) |
All collection resources share `.list()`, `.listAll()`, `.listPaginated()`, `.item()`, `.create()`, `.update()`, `.delete()`, `.describe()`. Pass `{ embed: true }` on `.item()` or `.list()` to request embedded data.
```
--------------------------------
### Export Posts to CSV with listAll()
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/examples/export-posts-csv.mdx
Use `.listAll()` to fetch all posts and then write them to a CSV file. This method handles the API's pagination automatically. Ensure the `node:fs` module is available for file operations.
```typescript
import { WordPressClient } from 'fluent-wp-client';
import { writeFileSync } from 'node:fs';
const wp = new WordPressClient({ baseUrl: 'https://example.com' });
const posts = await wp.content('posts').listAll({ status: 'publish' });
const header = ['id', 'slug', 'title', 'date', 'link'].join(',');
const rows = posts.map((p) =>
[p.id, p.slug, `"${p.title.rendered.replace(/
```
```typescript
("/", '""')}"`, p.date, p.link].join(',')
);
writeFileSync('posts.csv', [header, ...rows].join('\n'));
console.log(`Exported ${posts.length} posts.`);
```
--------------------------------
### Get Catalog Selectors for Agent Tooling
Source: https://context7.com/juvojustin/fluent-wp-client/llms.txt
Use getCatalogSelectors() to retrieve JSON Schema enum objects for resource families. This is useful for building framework-native tools that require selector inputs or discriminated unions. Ensure wp.explore() is called first to populate the catalog.
```typescript
await wp.explore(); // populate catalog
const selectors = await wp.getCatalogSelectors();
// selectors.contentType → { type: 'string', enum: ['posts', 'pages', 'books', ...] }
// selectors.taxonomyType → { type: 'string', enum: ['categories', 'tags', 'genre', ...] }
// selectors.resourceType → { type: 'string', enum: ['media', 'comments', 'users'] }
// selectors.abilityName → { type: 'string', enum: ['namespace/action', ...] }
```
```typescript
// Build a framework-specific tool using the discovered selector
const inputSchema = await wp.content('posts').getJsonSchema('create');
agent.registerTool({
name: 'create_post_draft',
description: 'Create a WordPress post draft. Never publishes content.',
inputSchema,
execute: async (input) => {
return wp.content('posts').create({ ...input, status: 'draft' });
},
});
```
--------------------------------
### Register Custom Tool with Fluent WP Client
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/agent-integration.mdx
Use this pattern to register a custom tool for creating WordPress post drafts. It requires initializing the WordPressClient, exploring the catalog, and defining the tool's input schema and execution logic.
```typescript
import { WordPressClient } from 'fluent-wp-client';
const wp = new WordPressClient({
baseUrl: 'https://example.com',
auth: { username: 'editor', password: 'app-password' },
});
await wp.explore();
const inputSchema = await wp.content('posts').getJsonSchema('create');
agent.registerTool({
name: 'create_post_draft',
description: 'Create a WordPress post draft. Never publishes content.',
inputSchema,
execute: async (input) => {
return wp.content('posts').create({ ...input, status: 'draft' });
},
});
```
--------------------------------
### Serialize and Restore WordPress Catalog
Source: https://context7.com/juvojustin/fluent-wp-client/llms.txt
Demonstrates serializing the discovered WordPress catalog to a key-value store and restoring it. This avoids repeated network calls for schema discovery, improving performance.
```typescript
// Serialize and restore to avoid repeated discovery round-trips
await kv.set('wp:catalog', JSON.stringify(catalog));
const stored = JSON.parse(await kv.get('wp:catalog') ?? 'null');
if (stored) wp.useCatalog(stored);
// describe() now resolves from cache without network calls
const desc = await wp.content('posts').describe();
console.log(desc.capabilities.queryParams);
```
--------------------------------
### Auth and ability helpers
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/usage.mdx
Lists available authentication and ability helper functions for managing authentication and executing abilities.
```APIDOC
### Auth and ability helpers
- `loginWithJwt(credentials)` / `validateJwtToken(token?)`
- `getAbilities()` / `getAbility(name)` / `getAbilityCategories()`
- `executeGetAbility()` / `executeRunAbility()` / `executeDeleteAbility()`
- `ability(name)` — fluent builder with `.get()`, `.run()`, `.delete()`, `.describe()`
```
--------------------------------
### Import All Generic Tool Families
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/ai-sdk.mdx
Import all available generic tool factories from the AI SDK for various WordPress resource types, including content, terms, resources, abilities, blocks, and settings.
```typescript
import {
// Content (posts, pages, custom post types)
getContentCollectionTool,
getContentTool,
saveContentTool,
deleteContentTool,
// Terms (categories, tags, custom taxonomies)
getTermCollectionTool,
getTermTool,
saveTermTool,
deleteTermTool,
// First-class resources (media, comments, users)
getResourceCollectionTool,
getResourceTool,
saveResourceTool,
deleteResourceTool,
// Abilities
getAbilitiesTool,
getAbilityTool,
executeGetAbilityTool,
executeRunAbilityTool,
executeDeleteAbilityTool,
createAbilityTools,
// Gutenberg blocks
getBlocksTool,
setBlocksTool,
// Settings
getSettingsTool,
updateSettingsTool,
// Schema introspection
describeResourceTool,
} from 'fluent-wp-client/ai-sdk';
```
--------------------------------
### Fetch All Posts with Default Concurrency
Source: https://context7.com/juvojustin/fluent-wp-client/llms.txt
Fetches all posts using the listAll() method with default concurrency settings. This method first determines the total count and then fetches remaining pages in batches.
```typescript
const allPosts = await wp.content('posts').listAll();
```
--------------------------------
### Generate Schema Files with CLI
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/validation.mdx
Use the `fluent-wp-client schemas` CLI command to generate schema files for build-time validation. Specify output paths for Zod and JSON schemas.
```bash
npx fluent-wp-client schemas \
--url https://example.com \
--zod-out src/lib/wp-schemas.ts \
--json-out src/lib/wp-schemas.json
```
--------------------------------
### Public WordPress Client
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/auth.mdx
Instantiate a WordPress client for public, read-only access without any authentication.
```typescript
const wp = new WordPressClient({ baseUrl: 'https://example.com' });
```
--------------------------------
### Custom Validation with describe()
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/abilities.mdx
Fetch live schemas using `describe()` for application-level validation before executing abilities.
```APIDOC
## Custom Validation with `describe()`
### Description
Fetch live schemas using `describe()` for application-level validation before executing abilities.
### Method
```ts
import { z } from 'zod';
const desc = await wp.ability('test/process-complex').describe();
const inputSchema = z.fromJSONSchema(desc.schemas.input!);
const outputSchema = z.fromJSONSchema(desc.schemas.output!);
const validatedInput = inputSchema.parse({
name: 'demo',
settings: { theme: 'dark' },
});
const result = await wp.ability('test/process-complex').run(validatedInput);
const validatedResult = outputSchema.parse(result);
```
```
--------------------------------
### Fluent Execution
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/abilities.mdx
Obtain a reusable ability handle using `client.ability(name)` for fluent execution with builder methods.
```APIDOC
## Fluent Execution
### Description
Obtain a reusable ability handle using `client.ability(name)` for fluent execution with builder methods.
### Method
```ts
const processComplex = wp
.ability<
{ name: string; settings: { theme: string } },
{ processed: boolean; echo: { name: string } }
>('test/process-complex')
;
const result = await processComplex.run({
name: 'demo',
settings: { theme: 'dark' },
});
```
### Builder Methods
- `getDefinition()`
- `get(input?)`
- `run(input?)`
- `delete(input?)`
- `describe()`
```
--------------------------------
### Create, Update, and Delete Users
Source: https://context7.com/juvojustin/fluent-wp-client/llms.txt
Manage user accounts including creation, updates, and deletion. User creation and modification require admin privileges.
```typescript
const created = await wp.users().create({ username: 'jsmith', email: 'j@example.com', password: 'secure123' });
```
```typescript
await wp.users().update(created.id, { first_name: 'John' });
```
```typescript
await wp.users().delete(created.id, { reassign: 1 });
```
--------------------------------
### Custom Post Type Reads
Source: https://github.com/juvojustin/fluent-wp-client/blob/main/docs/custom-endpoints.mdx
Demonstrates how to list, retrieve, and paginate custom post type items.
```APIDOC
## Custom Post Type Reads
Assume a CPT with `rest_base: 'books'`.
```ts
const books = wp.content('books');
// List items with pagination
const list = await books.list({ perPage: 20 });
// List all items
const allBooks = await books.listAll();
// List items with specific page and perPage
const paged = await books.listPaginated({ page: 2, perPage: 25 });
// Retrieve a single item by ID
const book = await books.item('my-book');
// Retrieve a single item with embedded related data
const embedded = await books.item('my-book', { embed: true });
```
:::note
CPT clients follow the same rules as core content builders: plain DTO reads stay lean, and `embed` opts into `_embed` on request.
:::
```