WordPress Development

Integrating AI Writing Assistants into WordPress: A Developer’s Guide

2024 is the year AI moved from experimentation to production in content workflows. OpenAI’s GPT-4 API, Anthropic’s Claude, and Google’s Gemini provide powerful text generation capabilities accessible via simple HTTP calls. For WordPress developers, the most impactful integration point is a custom Gutenberg block that puts AI assistance directly inside the editor.

Architecture Overview

The recommended approach keeps your OpenAI API key on the server, never exposed to the browser:

Gutenberg Block (JS)
    → WordPress REST API endpoint (PHP)
        → OpenAI API (server-to-server)
            ← Response back through the chain

WordPress REST Endpoint (PHP)

add_action( 'rest_api_init', function() {
    register_rest_route( 'aiw/v1', '/generate', [
        'methods'             => 'POST',
        'callback'            => 'aiw_generate_text',
        'permission_callback' => function() {
            return current_user_can( 'edit_posts' );
        },
        'args' => [
            'prompt' => [ 'required' => true, 'sanitize_callback' => 'sanitize_textarea_field' ],
        ],
    ] );
} );

function aiw_generate_text( WP_REST_Request $request ) {
    $api_key = get_option( 'aiw_openai_key' );
    $prompt  = $request->get_param( 'prompt' );

    $response = wp_remote_post( 'https://api.openai.com/v1/chat/completions', [
        'headers' => [
            'Authorization' => 'Bearer ' . $api_key,
            'Content-Type'  => 'application/json',
        ],
        'body' => wp_json_encode( [
            'model'    => 'gpt-4-turbo-preview',
            'messages' => [
                [ 'role' => 'system', 'content' => 'You are a helpful blog writing assistant.' ],
                [ 'role' => 'user',   'content' => $prompt ],
            ],
            'max_tokens' => 500,
        ] ),
        'timeout' => 30,
    ] );

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

    $body = json_decode( wp_remote_retrieve_body( $response ), true );
    return rest_ensure_response( [
        'text' => $body['choices'][0]['message']['content'] ?? '',
    ] );
}

Gutenberg Block (React)

const { useState } = wp.element;
const { Button, TextareaControl, Spinner } = wp.components;

registerBlockType( 'aiw/ai-writer', {
    title: 'AI Writer',
    edit: ( { setAttributes } ) => {
        const [prompt, setPrompt] = useState('');
        const [loading, setLoading] = useState(false);

        const generate = async () => {
            setLoading(true);
            const res = await wp.apiFetch({
                path: '/aiw/v1/generate',
                method: 'POST',
                data: { prompt },
            });
            setAttributes({ content: res.text });
            setLoading(false);
        };

        return (
            <div>
                <TextareaControl label="Prompt" value={prompt} onChange={setPrompt} />
                <Button isPrimary onClick={generate} disabled={loading}>
                    {loading ? <Spinner /> : 'Generate'}
                </Button>
            </div>
        );
    },
    save: ( { attributes } ) => <p>{attributes.content}</p>,
} );

Rate Limiting and Cost Control

Set a per-user daily generation limit stored in user meta, and use the cheaper gpt-4o-mini model for drafts and only gpt-4-turbo for final polish. Log all API calls with token counts for cost monitoring.

AI integration in WordPress is no longer a novelty — it’s a competitive advantage. Editors who can generate, refine, and polish content without leaving the block editor work dramatically faster.

Share this post:
Copied!

Leave a Comment

Your email will not be published.

READY TO BUILD?

Let's Build Something
Amazing Together

Tell us about your project. We'll have a proposal in your inbox within 24 hours.

Free Consultation
NDA Available
Fixed-price Options
Dedicated PM