Building AI Tools on WordPress: Adding OpenAI, Gemini, and Claude APIs to Your Site
在 WordPress 上构建 AI 工具:为您的网站添加 OpenAI、Gemini 和 Claude API

Want to build such a tool? 👇
想构建这样的工具吗?👇


AI Sentence Generator  AI 句子生成器

Enter a topic, choose a provider, and format:
输入一个主题,选择一个提供者,并设置格式:


 

In this guide, I’ll show you how to improve your WordPress site by integrating it with the top three LLM providers’ models: OpenAI’s GPT, Google’s Gemini, and Anthropic’s Claude.
在这个指南中,我将向你展示如何通过将其与前三家 LLM 提供商的模型集成来改进你的 WordPress 网站:OpenAI 的 GPT、Google 的 Gemini 和 Anthropic 的 Claude。

The best part? You don’t need advanced coding skills to make this happen.
最好的部分是?你不需要高级编程技能就能实现这一点。

All you need to do is follow this guide step by step, and you’ll be able to build your own AI tools by the end of this tutorial.
你需要做的就是按照这个指南一步步操作,到本教程结束时你就能构建自己的 AI 工具。

What We’re Building  我们正在构建的内容

We’ll create custom WordPress endpoints that connect directly to these AI services. You’ll get:
我们将创建自定义 WordPress 端点,直接连接到这些 AI 服务。您将获得:

  • Six custom API endpoints: three providers, each with two output formats (plain text and JSON)
    六个自定义 API 端点:三个提供者,每个提供者有两种输出格式(纯文本和 JSON)
  • A working frontend tool: letting visitors generate AI-powered text from your site
    一个可用的前端工具:让访客从您的网站生成 AI 驱动的文本
  • A clean and extendable codebase: perfect for adding more functionality later
    一个干净且可扩展的代码库:非常适合日后添加更多功能

Step 1: Install the Code Snippets Plugin
第一步:安装 Code Snippets 插件

Before we dive into the code, let’s set up the Code Snippets plugin. This will allow us to add functions to WordPress without directly editing theme files, which is so much easier.
在开始编写代码之前,让我们先设置 Code Snippets 插件。这将允许我们向 WordPress 添加功能,而无需直接编辑主题文件,这样会简单得多。

  1. Log in to your WordPress admin dashboard
    登录到您的 WordPress 管理后台
  2. Go to Plugins > Add New
    进入插件 > 添加新插件
  3. Search for “Code Snippets”
    搜索“Code Snippets”

4. Once you find the one above (it should be the first one), click “Install Now” and then “Activate.”
4. 找到上述选项(它应该是第一个),点击“立即安装”,然后“激活”。

Once installed, you’ll have a new “Snippets” menu item in your WordPress admin. This is where we’ll add our code.
安装后,您将在 WordPress 管理后台看到一个新的“代码片段”菜单项。我们将在这里添加代码。

Step 2: Getting Your API Keys
第二步:获取您的 API 密钥

Before we start coding, you’ll need API keys from each provider. Here’s how to get them:
在开始编码之前,您需要从每个提供商那里获取 API 密钥。以下是获取它们的方法:

OpenAI API Key  OpenAI API 密钥

  1. Visit OpenAI’s platform  访问 OpenAI 的平台
  2. Create an account or log in
    创建账户或登录
  3. Go to the API keys section and create a new secret key
    前往 API 密钥部分并创建一个新的密钥
  4. Copy and store it securely (you won’t be able to see it again)
    复制并安全存储(你将无法再次看到它)

OpenAI offers several models, so make sure to check their pricing page for details.
OpenAI 提供多个模型,请务必查看其定价页面以获取详细信息。

Google Gemini API Key
Google Gemini API 密钥

  1. Go to Google AI Studio
    前往 Google AI Studio
  2. Sign in with your Google account
    使用您的 Google 账户登录
  3. Create an API key using the button in the top right corner.
    使用右上角按钮创建 API 密钥。
  4. Copy and store it securely
    复制并安全存储它

See Google AI pricing for details about the pricing of each model.
查看 Google AI 定价详情以了解每个模型的定价。

Anthropic API Key  Anthropic API 密钥

  1. Visit Anthropic Console  访问 Anthropic 控制台
  2. Create an account or sign in
    创建账户或登录
  3. Navigate to the API Keys section
    导航至 API 密钥部分
  4. Generate a new API key
    生成新的 API 密钥

Check their pricing details for detailed pricing for each model.
查看他们的定价详情,以获取每个模型的详细价格。

Step 3: Add Code Snippets for Each LLM Provider
步骤 3:为每个 LLM 提供商添加代码片段

We’ll now register REST API endpoints in WordPress using the Code Snippets plugin. Each provider (OpenAI, Gemini, Claude) will have two endpoints:
现在我们将使用 Code Snippets 插件在 WordPress 中注册 REST API 端点。每个提供商(OpenAI、Gemini、Claude)将有两个端点:

  • /ai-tools/v1/[provider] → returns plain text
    /ai-tools/v1/[provider] → 返回纯文本
  • /ai-tools/v1/[provider]-json → returns structured JSON
    /ai-tools/v1/[provider]-json → 返回结构化 JSON

OpenAI Integration  OpenAI 集成

First, go to the code snippets plugin we just downloaded, and create a new snippet named OpenAI REST Endpoint:
首先,前往我们刚刚下载的代码片段插件,创建一个名为 OpenAI REST Endpoint 的新片段:

Now, paste the below code in the code section:
现在,将以下代码粘贴到代码部分:

function blog_call_openai_api($topic, $return_json = false) {
$prompt = "generate for me a 5 word sentence about $topic";
$api_key = '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';
$url = 'https://api.openai.com/v1/chat/completions';
$body_data = [
'model' => 'gpt-4o-mini',
'messages' => [[ 'role' => 'user', 'content' => $prompt ]],
'max_tokens' => $return_json ? 50 : 20,
'temperature' => 0.7
];
if ($return_json) {
$body_data['response_format'] = [
'type' => 'json_schema',
'json_schema' => [
'name' => 'sentence_response',
'strict' => true,
'schema' => [
'type' => 'object',
'properties' => [
'sentence' => [
'type' => 'string',
'description' => 'A 5 word sentence about the given topic'
]
],
'required' => ['sentence'],
'additionalProperties' => false
]
]
];
}
$response = wp_remote_post($url, [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key
],
'body' => json_encode($body_data)
]);
if (is_wp_error($response)) return $response;
$body = json_decode(wp_remote_retrieve_body($response), true);
if ($return_json) {
return json_decode($body['choices'][0]['message']['content'], true);
} else {
return trim($body['choices'][0]['message']['content']);
}
}
function blog_call_openai_api($topic, $return_json = false) { $prompt = "generate for me a 5 word sentence about $topic"; $api_key = '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'; $url = 'https://api.openai.com/v1/chat/completions'; $body_data = [ 'model' => 'gpt-4o-mini', 'messages' => [[ 'role' => 'user', 'content' => $prompt ]], 'max_tokens' => $return_json ? 50 : 20, 'temperature' => 0.7 ]; if ($return_json) { $body_data['response_format'] = [ 'type' => 'json_schema', 'json_schema' => [ 'name' => 'sentence_response', 'strict' => true, 'schema' => [ 'type' => 'object', 'properties' => [ 'sentence' => [ 'type' => 'string', 'description' => 'A 5 word sentence about the given topic' ] ], 'required' => ['sentence'], 'additionalProperties' => false ] ] ]; } $response = wp_remote_post($url, [ 'headers' => [ 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $api_key ], 'body' => json_encode($body_data) ]); if (is_wp_error($response)) return $response; $body = json_decode(wp_remote_retrieve_body($response), true); if ($return_json) { return json_decode($body['choices'][0]['message']['content'], true); } else { return trim($body['choices'][0]['message']['content']); } }
function blog_call_openai_api($topic, $return_json = false) {
    $prompt = "generate for me a 5 word sentence about $topic";
    $api_key = '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';
    $url = 'https://api.openai.com/v1/chat/completions';

    $body_data = [
        'model' => 'gpt-4o-mini',
        'messages' => [[ 'role' => 'user', 'content' => $prompt ]],
        'max_tokens' => $return_json ? 50 : 20,
        'temperature' => 0.7
    ];

    if ($return_json) {
        $body_data['response_format'] = [
            'type' => 'json_schema',
            'json_schema' => [
                'name' => 'sentence_response',
                'strict' => true,
                'schema' => [
                    'type' => 'object',
                    'properties' => [
                        'sentence' => [
                            'type' => 'string',
                            'description' => 'A 5 word sentence about the given topic'
                        ]
                    ],
                    'required' => ['sentence'],
                    'additionalProperties' => false
                ]
            ]
        ];
    }

    $response = wp_remote_post($url, [
        'headers' => [
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $api_key
        ],
        'body' => json_encode($body_data)
    ]);

    if (is_wp_error($response)) return $response;
    $body = json_decode(wp_remote_retrieve_body($response), true);
    
    if ($return_json) {
        return json_decode($body['choices'][0]['message']['content'], true);
    } else {
        return trim($body['choices'][0]['message']['content']);
    }
}

Make sure you add your own API key, instead of the placeholder. Now, to choose whether you want to return json or text output format, add these two functions after the function above:
确保添加你自己的 API 密钥,而不是占位符。现在,为了选择你想返回的 json 或文本输出格式,在上述函数后添加这两个函数:

function blog_generate_openai_text($request) {
$topic = $request->get_param('topic');
$sentence = blog_call_openai_api($topic, false);
if (is_wp_error($sentence)) return $sentence;
return new WP_REST_Response($sentence, 200, ['Content-Type' => 'text/plain']);
}
function blog_generate_openai_json($request) {
$topic = $request->get_param('topic');
$result = blog_call_openai_api($topic, true);
if (is_wp_error($result)) return $result;
return $result;
}
function blog_generate_openai_text($request) { $topic = $request->get_param('topic'); $sentence = blog_call_openai_api($topic, false); if (is_wp_error($sentence)) return $sentence; return new WP_REST_Response($sentence, 200, ['Content-Type' => 'text/plain']); } function blog_generate_openai_json($request) { $topic = $request->get_param('topic'); $result = blog_call_openai_api($topic, true); if (is_wp_error($result)) return $result; return $result; }
function blog_generate_openai_text($request) {
    $topic = $request->get_param('topic');
    $sentence = blog_call_openai_api($topic, false);
    if (is_wp_error($sentence)) return $sentence;
    return new WP_REST_Response($sentence, 200, ['Content-Type' => 'text/plain']);
}

function blog_generate_openai_json($request) {
    $topic = $request->get_param('topic');
    $result = blog_call_openai_api($topic, true);
    if (is_wp_error($result)) return $result;
    return $result;
}

Finally, register both endpoints so we can access them easily from anywhere, by adding the below code:
最后,注册这两个端点,以便我们可以从任何地方轻松访问它们,通过添加以下代码:

add_action('rest_api_init', function () {
register_rest_route('ai-tools/v1', '/openai', [
'methods' => 'GET',
'callback' => 'blog_generate_openai_text',
'args' => [
'topic' => [ 'required' => true, 'sanitize_callback' => 'sanitize_text_field' ]
],
'permission_callback' => '__return_true'
]);
register_rest_route('ai-tools/v1', '/openai-json', [
'methods' => 'GET',
'callback' => 'blog_generate_openai_json',
'args' => [
'topic' => [ 'required' => true, 'sanitize_callback' => 'sanitize_text_field' ]
],
'permission_callback' => '__return_true'
]);
});
add_action('rest_api_init', function () { register_rest_route('ai-tools/v1', '/openai', [ 'methods' => 'GET', 'callback' => 'blog_generate_openai_text', 'args' => [ 'topic' => [ 'required' => true, 'sanitize_callback' => 'sanitize_text_field' ] ], 'permission_callback' => '__return_true' ]); register_rest_route('ai-tools/v1', '/openai-json', [ 'methods' => 'GET', 'callback' => 'blog_generate_openai_json', 'args' => [ 'topic' => [ 'required' => true, 'sanitize_callback' => 'sanitize_text_field' ] ], 'permission_callback' => '__return_true' ]); });
add_action('rest_api_init', function () {
    register_rest_route('ai-tools/v1', '/openai', [
        'methods' => 'GET',
        'callback' => 'blog_generate_openai_text',
        'args' => [
            'topic' => [ 'required' => true, 'sanitize_callback' => 'sanitize_text_field' ]
        ],
        'permission_callback' => '__return_true'
    ]);

    register_rest_route('ai-tools/v1', '/openai-json', [
        'methods' => 'GET',
        'callback' => 'blog_generate_openai_json',
        'args' => [
            'topic' => [ 'required' => true, 'sanitize_callback' => 'sanitize_text_field' ]
        ],
        'permission_callback' => '__return_true'
    ]);
});

Google Gemini Integration
Google Gemini 集成

Repeat the same structure as we did with OpenAI for Gemini. Create a snippet called Gemini REST Endpoint:
重复我们为 OpenAI 所做的那样,为 Gemini 创建一个名为 Gemini REST Endpoint 的片段:

function blog_call_gemini_api($topic, $return_json = false) {
$prompt = "generate for me a 5 word sentence about $topic";
$api_key = 'AIzaSyAMtQe4_jzJGG-wPn6mSIMH_wKEGHIfQZ0';
$url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$api_key";
$body_data = [
'contents' => [[ 'parts' => [[ 'text' => $prompt ]] ]]
];
if ($return_json) {
$body_data['generationConfig'] = [
'response_mime_type' => 'application/json',
'response_schema' => [
'type' => 'object',
'properties' => [
'sentence' => [
'type' => 'string',
'description' => 'A 5 word sentence about the given topic'
]
],
'required' => ['sentence']
]
];
}
$response = wp_remote_post($url, [
'headers' => ['Content-Type' => 'application/json'],
'body' => json_encode($body_data)
]);
if (is_wp_error($response)) return $response;
$body = json_decode(wp_remote_retrieve_body($response), true);
if ($return_json) {
return json_decode($body['candidates'][0]['content']['parts'][0]['text'], true);
} else {
return trim($body['candidates'][0]['content']['parts'][0]['text']);
}
}
function blog_call_gemini_api($topic, $return_json = false) { $prompt = "generate for me a 5 word sentence about $topic"; $api_key = 'AIzaSyAMtQe4_jzJGG-wPn6mSIMH_wKEGHIfQZ0'; $url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$api_key"; $body_data = [ 'contents' => [[ 'parts' => [[ 'text' => $prompt ]] ]] ]; if ($return_json) { $body_data['generationConfig'] = [ 'response_mime_type' => 'application/json', 'response_schema' => [ 'type' => 'object', 'properties' => [ 'sentence' => [ 'type' => 'string', 'description' => 'A 5 word sentence about the given topic' ] ], 'required' => ['sentence'] ] ]; } $response = wp_remote_post($url, [ 'headers' => ['Content-Type' => 'application/json'], 'body' => json_encode($body_data) ]); if (is_wp_error($response)) return $response; $body = json_decode(wp_remote_retrieve_body($response), true); if ($return_json) { return json_decode($body['candidates'][0]['content']['parts'][0]['text'], true); } else { return trim($body['candidates'][0]['content']['parts'][0]['text']); } }
function blog_call_gemini_api($topic, $return_json = false) {
    $prompt = "generate for me a 5 word sentence about $topic";
    $api_key = 'AIzaSyAMtQe4_jzJGG-wPn6mSIMH_wKEGHIfQZ0';
    $url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$api_key";

    $body_data = [
        'contents' => [[ 'parts' => [[ 'text' => $prompt ]] ]]
    ];

    if ($return_json) {
        $body_data['generationConfig'] = [
            'response_mime_type' => 'application/json',
            'response_schema' => [
                'type' => 'object',
                'properties' => [
                    'sentence' => [
                        'type' => 'string',
                        'description' => 'A 5 word sentence about the given topic'
                    ]
                ],
                'required' => ['sentence']
            ]
        ];
    }

    $response = wp_remote_post($url, [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => json_encode($body_data)
    ]);

    if (is_wp_error($response)) return $response;
    $body = json_decode(wp_remote_retrieve_body($response), true);
    
    if ($return_json) {
        return json_decode($body['candidates'][0]['content']['parts'][0]['text'], true);
    } else {
        return trim($body['candidates'][0]['content']['parts'][0]['text']);
    }
}

Also, don’t forget to add your own API key instead of the placeholder. Then, add these two endpoints:
此外,别忘了将占位符替换为您自己的 API 密钥。然后,添加这两个端点:

function blog_generate_gemini_text($request) {
$topic = $request->get_param('topic');
$sentence = blog_call_gemini_api($topic, false);
if (is_wp_error($sentence)) return $sentence;
return new WP_REST_Response($sentence, 200, ['Content-Type' => 'text/plain']);
}
function blog_generate_gemini_json($request) {
$topic = $request->get_param('topic');
$result = blog_call_gemini_api($topic, true);
if (is_wp_error($result)) return $result;
return $result;
}
add_action('rest_api_init', function () {
register_rest_route('ai-tools/v1', '/gemini', [
'methods' => 'GET',
'callback' => 'blog_generate_gemini_text',
'args' => [
'topic' => [ 'required' => true, 'sanitize_callback' => 'sanitize_text_field' ]
],
'permission_callback' => '__return_true'
]);
register_rest_route('ai-tools/v1', '/gemini-json', [
'methods' => 'GET',
'callback' => 'blog_generate_gemini_json',
'args' => [
'topic' => [ 'required' => true, 'sanitize_callback' => 'sanitize_text_field' ]
],
'permission_callback' => '__return_true'
]);
});
function blog_generate_gemini_text($request) { $topic = $request->get_param('topic'); $sentence = blog_call_gemini_api($topic, false); if (is_wp_error($sentence)) return $sentence; return new WP_REST_Response($sentence, 200, ['Content-Type' => 'text/plain']); } function blog_generate_gemini_json($request) { $topic = $request->get_param('topic'); $result = blog_call_gemini_api($topic, true); if (is_wp_error($result)) return $result; return $result; } add_action('rest_api_init', function () { register_rest_route('ai-tools/v1', '/gemini', [ 'methods' => 'GET', 'callback' => 'blog_generate_gemini_text', 'args' => [ 'topic' => [ 'required' => true, 'sanitize_callback' => 'sanitize_text_field' ] ], 'permission_callback' => '__return_true' ]); register_rest_route('ai-tools/v1', '/gemini-json', [ 'methods' => 'GET', 'callback' => 'blog_generate_gemini_json', 'args' => [ 'topic' => [ 'required' => true, 'sanitize_callback' => 'sanitize_text_field' ] ], 'permission_callback' => '__return_true' ]); });
function blog_generate_gemini_text($request) {
    $topic = $request->get_param('topic');
    $sentence = blog_call_gemini_api($topic, false);
    if (is_wp_error($sentence)) return $sentence;
    return new WP_REST_Response($sentence, 200, ['Content-Type' => 'text/plain']);
}

function blog_generate_gemini_json($request) {
    $topic = $request->get_param('topic');
    $result = blog_call_gemini_api($topic, true);
    if (is_wp_error($result)) return $result;
    return $result;
}

add_action('rest_api_init', function () {
    register_rest_route('ai-tools/v1', '/gemini', [
        'methods' => 'GET',
        'callback' => 'blog_generate_gemini_text',
        'args' => [
            'topic' => [ 'required' => true, 'sanitize_callback' => 'sanitize_text_field' ]
        ],
        'permission_callback' => '__return_true'
    ]);

    register_rest_route('ai-tools/v1', '/gemini-json', [
        'methods' => 'GET',
        'callback' => 'blog_generate_gemini_json',
        'args' => [
            'topic' => [ 'required' => true, 'sanitize_callback' => 'sanitize_text_field' ]
        ],
        'permission_callback' => '__return_true'
    ]);
});

Claude (Anthropic) Integration
Claude (Anthropic) 集成

Claude works similarly, but with a slightly different structure. Create a snippet Claude REST Endpoint:
Claude 的工作方式类似,但结构略有不同。创建一个 Claude REST 端点片段:

function blog_call_claude_api($topic, $return_json = false) {
$prompt = "generate for me a 5 word sentence about $topic";
$api_key = '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';
$body_data = [
'model' => 'claude-3-sonnet-20240229',
'max_tokens' => 100,
'messages' => [[ 'role' => 'user', 'content' => $prompt ]]
];
if ($return_json) {
$body_data['system'] = 'You must always respond with valid JSON only. Return your response in this exact format: {"sentence": "your response here"}. Do not include any other text, explanations, or formatting.';
}
$response = wp_remote_post('https://api.anthropic.com/v1/messages', [
'headers' => [
'Content-Type' => 'application/json',
'x-api-key' => $api_key,
'anthropic-version' => '2023-06-01'
],
'body' => json_encode($body_data)
]);
if (is_wp_error($response)) return $response;
$body = json_decode(wp_remote_retrieve_body($response), true);
if ($return_json) {
return json_decode($body['content'][0]['text'], true);
} else {
return trim($body['content'][0]['text']);
}
}
function blog_call_claude_api($topic, $return_json = false) { $prompt = "generate for me a 5 word sentence about $topic"; $api_key = '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'; $body_data = [ 'model' => 'claude-3-sonnet-20240229', 'max_tokens' => 100, 'messages' => [[ 'role' => 'user', 'content' => $prompt ]] ]; if ($return_json) { $body_data['system'] = 'You must always respond with valid JSON only. Return your response in this exact format: {"sentence": "your response here"}. Do not include any other text, explanations, or formatting.'; } $response = wp_remote_post('https://api.anthropic.com/v1/messages', [ 'headers' => [ 'Content-Type' => 'application/json', 'x-api-key' => $api_key, 'anthropic-version' => '2023-06-01' ], 'body' => json_encode($body_data) ]); if (is_wp_error($response)) return $response; $body = json_decode(wp_remote_retrieve_body($response), true); if ($return_json) { return json_decode($body['content'][0]['text'], true); } else { return trim($body['content'][0]['text']); } }
function blog_call_claude_api($topic, $return_json = false) {
    $prompt = "generate for me a 5 word sentence about $topic";
    $api_key = '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';

    $body_data = [
        'model' => 'claude-3-sonnet-20240229',
        'max_tokens' => 100,
        'messages' => [[ 'role' => 'user', 'content' => $prompt ]]
    ];

    if ($return_json) {
        $body_data['system'] = 'You must always respond with valid JSON only. Return your response in this exact format: {"sentence": "your response here"}. Do not include any other text, explanations, or formatting.';
    }

    $response = wp_remote_post('https://api.anthropic.com/v1/messages', [
        'headers' => [
            'Content-Type' => 'application/json',
            'x-api-key' => $api_key,
            'anthropic-version' => '2023-06-01'
        ],
        'body' => json_encode($body_data)
    ]);

    if (is_wp_error($response)) return $response;
    $body = json_decode(wp_remote_retrieve_body($response), true);
    
    if ($return_json) {
        return json_decode($body['content'][0]['text'], true);
    } else {
        return trim($body['content'][0]['text']);
    }
}

Add your own API key, then after it, add these corresponding routes:
添加您自己的 API 密钥,然后在其后添加相应的路由:

function blog_generate_claude_text($request) {
$topic = $request->get_param('topic');
$sentence = blog_call_claude_api($topic, false);
if (is_wp_error($sentence)) return $sentence;
return new WP_REST_Response($sentence, 200, ['Content-Type' => 'text/plain']);
}
function blog_generate_claude_json($request) {
$topic = $request->get_param('topic');
$result = blog_call_claude_api($topic, true);
if (is_wp_error($result)) return $result;
return $result;
}
add_action('rest_api_init', function () {
register_rest_route('ai-tools/v1', '/claude', [
'methods' => 'GET',
'callback' => 'blog_generate_claude_text',
'args' => [
'topic' => [ 'required' => true, 'sanitize_callback' => 'sanitize_text_field' ]
],
'permission_callback' => '__return_true'
]);
register_rest_route('ai-tools/v1', '/claude-json', [
'methods' => 'GET',
'callback' => 'blog_generate_claude_json',
'args' => [
'topic' => [ 'required' => true, 'sanitize_callback' => 'sanitize_text_field' ]
],
'permission_callback' => '__return_true'
]);
});
function blog_generate_claude_text($request) { $topic = $request->get_param('topic'); $sentence = blog_call_claude_api($topic, false); if (is_wp_error($sentence)) return $sentence; return new WP_REST_Response($sentence, 200, ['Content-Type' => 'text/plain']); } function blog_generate_claude_json($request) { $topic = $request->get_param('topic'); $result = blog_call_claude_api($topic, true); if (is_wp_error($result)) return $result; return $result; } add_action('rest_api_init', function () { register_rest_route('ai-tools/v1', '/claude', [ 'methods' => 'GET', 'callback' => 'blog_generate_claude_text', 'args' => [ 'topic' => [ 'required' => true, 'sanitize_callback' => 'sanitize_text_field' ] ], 'permission_callback' => '__return_true' ]); register_rest_route('ai-tools/v1', '/claude-json', [ 'methods' => 'GET', 'callback' => 'blog_generate_claude_json', 'args' => [ 'topic' => [ 'required' => true, 'sanitize_callback' => 'sanitize_text_field' ] ], 'permission_callback' => '__return_true' ]); });
function blog_generate_claude_text($request) {
    $topic = $request->get_param('topic');
    $sentence = blog_call_claude_api($topic, false);
    if (is_wp_error($sentence)) return $sentence;
    return new WP_REST_Response($sentence, 200, ['Content-Type' => 'text/plain']);
}

function blog_generate_claude_json($request) {
    $topic = $request->get_param('topic');
    $result = blog_call_claude_api($topic, true);
    if (is_wp_error($result)) return $result;
    return $result;
}

add_action('rest_api_init', function () {
    register_rest_route('ai-tools/v1', '/claude', [
        'methods' => 'GET',
        'callback' => 'blog_generate_claude_text',
        'args' => [
            'topic' => [ 'required' => true, 'sanitize_callback' => 'sanitize_text_field' ]
        ],
        'permission_callback' => '__return_true'
    ]);

    register_rest_route('ai-tools/v1', '/claude-json', [
        'methods' => 'GET',
        'callback' => 'blog_generate_claude_json',
        'args' => [
            'topic' => [ 'required' => true, 'sanitize_callback' => 'sanitize_text_field' ]
        ],
        'permission_callback' => '__return_true'
    ]);
});

Each of these handlers isolates the logic and provides both human-friendly and developer-friendly outputs depending on the endpoint and the output structure you are looking for.
每个这些处理器都隔离了逻辑,并根据您要查找的端点和输出结构提供对人类友好和开发者友好的输出。

Step 4: Understanding What We Just Built
第 4 步:理解我们刚刚构建的内容

Let’s break down the code we just created:
让我们来分解一下我们刚刚创建的代码:

  • Each provider has a core API function (blog_call_openai_api(), blog_call_gemini_api(), blog_call_claude_api()) that sends a POST request to the provider’s LLM with a fixed prompt.
    每个提供商都有一个核心 API 函数( blog_call_openai_api()blog_call_gemini_api()blog_call_claude_api() ),该函数向提供商的 LLM 发送一个带有固定提示的 POST 请求。
  • We define two REST endpoints per provider — one returns plain text (for human consumption), and the other returns JSON (for programmatic use).
    我们为每个提供商定义了两个 REST 端点——一个返回纯文本(供人类使用),另一个返回 JSON(供程序使用)。
  • All endpoints accept a single input (query parameter): ?topic=...
    所有端点都接受一个输入(查询参数): ?topic=..

Step 5: Test Your Endpoints with Postman
第 5 步:使用 Postman 测试您的端点

Before building the frontend, let’s test if our endpoints are working properly. So, download Postman, which will help us easily test the endpoints:
在构建前端之前,让我们测试一下我们的端点是否正常工作。因此,下载 Postman,它将帮助我们轻松测试端点:

  1. Open Postman  打开 Postman
  2. Set the request method to GET
    将请求方法设置为 GET
  3. Use a URL like: https://YOURDOMAIN.com/wp-json/ai-tools/v1/openai?topic=flowers
    使用类似 https://YOURDOMAIN.com/wp-json/ai-tools/v1/openai?topic=flowers 的 URL
  4. Click Send  点击发送

Here’s an example from my case:
以下是我案例中的示例:

test endpoint with postman

As you can see, since I chose the JSON-formatted output, I got: {"sentence": "Robots eddiciently perform complex tasks"}
如您所见,因为我选择了 JSON 格式的输出,我得到了: {"sentence": "Robots eddiciently perform complex tasks"}

If I choose the normal output, here is how the test will look:
如果我选择普通输出,测试将如下所示:

Do this for each of the six endpoints; don’t move on to the next step unless all of them work properly.
为这六个端点中的每一个执行此操作;除非所有它们都正常工作,否则不要继续下一步。

If something doesn’t work, check the API key and URL. If you can’t find what’s wrong, feel free to add your questions to the free public forum.
如果某项功能无法正常工作,请检查 API 密钥和 URL。如果您找不到问题所在,欢迎将您的问题添加到免费公共论坛。

Step 5: Building a Simple Frontend Tool
第 5 步:构建一个简单的前端工具

Now let’s create a simple tool that users can interact with.
现在让我们创建一个用户可以与之交互的简单工具。

First, create a new page on your website and add an HTML block to it like this:
首先,在您的网站上创建一个新页面,并像这样添加一个 HTML 模块:

Choose it, and paste the following code inside it:
选择它,并在其中粘贴以下代码:

<div id="ai-tool" style="max-width: 600px; margin: auto; font-family: sans-serif;">
<h2>AI Sentence Generator</h2>
<p>Enter a topic, choose a provider, and format:</p>
<input type="text" id="topic" placeholder="Enter topic..." style="width: 100%; padding: 10px; margin-bottom: 10px;">
<div style="display: flex; gap: 10px; margin-bottom: 10px;">
<select id="provider" style="flex: 1; padding: 10px;">
<option value="gemini">Gemini</option>
<option value="claude">Claude</option>
<option value="openai">OpenAI</option>
</select>
<select id="format" style="flex: 1; padding: 10px;">
<option value="">Text</option>
<option value="-json">JSON</option>
</select>
</div>
<button onclick="generateSentence()" style="padding: 10px 20px; background: #2271b1; color: white; border: none; border-radius: 4px; cursor: pointer;">Generate</button>
<pre id="result" style="margin-top: 20px; background: #f1f1f1; padding: 15px; border-radius: 4px; min-height: 60px;"></pre>
</div>
<script>
function generateSentence() {
const topic = document.getElementById('topic').value;
const provider = document.getElementById('provider').value;
const format = document.getElementById('format').value;
const result = document.getElementById('result');
if (!topic) {
result.textContent = 'Please enter a topic.';
return;
}
result.textContent = 'Loading...';
fetch(`/wp-json/ai-tools/v1/${provider}${format}?topic=${encodeURIComponent(topic)}`)
.then(res => res.ok ? res.text() : Promise.reject(res.statusText))
.then(text => {
try {
const json = JSON.parse(text);
result.textContent = JSON.stringify(json, null, 2);
} catch (e) {
result.textContent = text;
}
})
.catch(err => {
result.textContent = 'Error: ' + err;
});
}
</script>
<div id="ai-tool" style="max-width: 600px; margin: auto; font-family: sans-serif;"> <h2>AI Sentence Generator</h2> <p>Enter a topic, choose a provider, and format:</p> <input type="text" id="topic" placeholder="Enter topic..." style="width: 100%; padding: 10px; margin-bottom: 10px;"> <div style="display: flex; gap: 10px; margin-bottom: 10px;"> <select id="provider" style="flex: 1; padding: 10px;"> <option value="gemini">Gemini</option> <option value="claude">Claude</option> <option value="openai">OpenAI</option> </select> <select id="format" style="flex: 1; padding: 10px;"> <option value="">Text</option> <option value="-json">JSON</option> </select> </div> <button onclick="generateSentence()" style="padding: 10px 20px; background: #2271b1; color: white; border: none; border-radius: 4px; cursor: pointer;">Generate</button> <pre id="result" style="margin-top: 20px; background: #f1f1f1; padding: 15px; border-radius: 4px; min-height: 60px;"></pre> </div> <script> function generateSentence() { const topic = document.getElementById('topic').value; const provider = document.getElementById('provider').value; const format = document.getElementById('format').value; const result = document.getElementById('result'); if (!topic) { result.textContent = 'Please enter a topic.'; return; } result.textContent = 'Loading...'; fetch(`/wp-json/ai-tools/v1/${provider}${format}?topic=${encodeURIComponent(topic)}`) .then(res => res.ok ? res.text() : Promise.reject(res.statusText)) .then(text => { try { const json = JSON.parse(text); result.textContent = JSON.stringify(json, null, 2); } catch (e) { result.textContent = text; } }) .catch(err => { result.textContent = 'Error: ' + err; }); } </script>
<div id="ai-tool" style="max-width: 600px; margin: auto; font-family: sans-serif;">
  <h2>AI Sentence Generator</h2>
  <p>Enter a topic, choose a provider, and format:</p>
  <input type="text" id="topic" placeholder="Enter topic..." style="width: 100%; padding: 10px; margin-bottom: 10px;">

  <div style="display: flex; gap: 10px; margin-bottom: 10px;">
    <select id="provider" style="flex: 1; padding: 10px;">
      <option value="gemini">Gemini</option>
      <option value="claude">Claude</option>
      <option value="openai">OpenAI</option>
    </select>
    <select id="format" style="flex: 1; padding: 10px;">
      <option value="">Text</option>
      <option value="-json">JSON</option>
    </select>
  </div>

  <button onclick="generateSentence()" style="padding: 10px 20px; background: #2271b1; color: white; border: none; border-radius: 4px; cursor: pointer;">Generate</button>

  <pre id="result" style="margin-top: 20px; background: #f1f1f1; padding: 15px; border-radius: 4px; min-height: 60px;"></pre>
</div>

<script>
function generateSentence() {
  const topic = document.getElementById('topic').value;
  const provider = document.getElementById('provider').value;
  const format = document.getElementById('format').value;
  const result = document.getElementById('result');

  if (!topic) {
    result.textContent = 'Please enter a topic.';
    return;
  }

  result.textContent = 'Loading...';

  fetch(`/wp-json/ai-tools/v1/${provider}${format}?topic=${encodeURIComponent(topic)}`)
    .then(res => res.ok ? res.text() : Promise.reject(res.statusText))
    .then(text => {
      try {
        const json = JSON.parse(text);
        result.textContent = JSON.stringify(json, null, 2);
      } catch (e) {
        result.textContent = text;
      }
    })
    .catch(err => {
      result.textContent = 'Error: ' + err;
    });
}
</script>

After adding the code, you’ll have something like this:
添加代码后,您将得到类似这样的效果:

After that, publish it, and let’s visit the page to test it:
之后,发布它,让我们访问页面来测试它:

Keep Building: What’s Next?
继续构建:接下来做什么?

With this setup, you’ve built a foundational AI layer for WordPress. You can:
有了这个设置,你已经为 WordPress 构建了一个基础 AI 层。你可以:

  • Add support for more models or languages
    添加更多模型或语言的支持
  • Track usage per user or session
    按用户或会话跟踪使用情况
  • Turn this into a micro-SaaS or member-only tool
    将其转变为微型 SaaS 或仅限会员的工具

And if you’re ready to go even deeper into AI-powered WordPress development, check out my SAAS 2.0 course, where we take this from a simple API integration to a full-blown business platform.
如果你已准备好深入探索 AI 驱动的 WordPress 开发,可以查看我的 SAAS 2.0 课程,在那里我们将从简单的 API 集成扩展到一个完整的商业平台。

Let me know what you build next. Share it in the comments section or on the forum 🚀
告诉我你接下来要构建什么。在评论区或论坛上分享它 🚀

Related Articles  相关文章

How To Create a Free AI Chatbot on WordPress From Scratch!
如何从零开始在 WordPress 上创建免费 AI 聊天机器人!

In this post, I will show you how to create a Free AI Chatbot on a WordPress site WITHOUT using third-party services or chatbot plugins.…
在这篇文章中,我将向你展示如何在 WordPress 网站上创建免费 AI 聊天机器人,而无需使用第三方服务或聊天机器人插件……

Extract & Analyze YouTube Comments With Python and YouTube API To Boost Your Marketing!
使用 Python 和 YouTube API 提取和分析 YouTube 评论,提升你的营销效果!

In this post, I will show you how to extract YouTube comments from your channel and turn them into valuable data for your marketing campaigns.…
在这篇文章中,我将向你展示如何从你的频道中提取 YouTube 评论,并将它们转化为对你营销活动有价值的数据……