DEVSAIO

Add an AI writing assistant to WordPress with PHP

A small WordPress plugin that generates excerpts and meta descriptions from post content using any model.

DEVSAIO team · 2 min read
Share on X

This mini-plugin adds a button on the post editor screen that writes an excerpt from the post content.

The plugin file

Create wp-content/plugins/ai-excerpt/ai-excerpt.php:

php
<?php
/*
Plugin Name: AI Excerpt
Description: Generate post excerpts with AI.
Version: 1.0
*/

add_action('wp_ajax_ai_excerpt', function () {
    check_ajax_referer('ai_excerpt');
    $post = get_post((int) ($_POST['post_id'] ?? 0));
    if (!$post || !current_user_can('edit_post', $post->ID)) { wp_send_json_error('Not allowed', 403); }

    $content = wp_strip_all_tags($post->post_content);
    $res = wp_remote_post('https://devsaio.lol/v1/chat/completions', [
        'timeout' => 60,
        'headers' => ['Authorization' => 'Bearer ' . AI_EXCERPT_KEY, 'Content-Type' => 'application/json'],
        'body' => wp_json_encode([
            'model' => 'claude-haiku-5-5',
            'max_tokens' => 120,
            'messages' => [['role' => 'user', 'content' => "Write a compelling 140-160 character excerpt for this article. No quotes.\n\n" . mb_substr($content, 0, 12000)]],
        ]),
    ]);
    if (is_wp_error($res)) { wp_send_json_error($res->get_error_message(), 502); }
    $data = json_decode(wp_remote_retrieve_body($res), true);
    $excerpt = trim($data['choices'][0]['message']['content'] ?? '');
    if ($excerpt === '') { wp_send_json_error('No answer', 502); }
    wp_update_post(['ID' => $post->ID, 'post_excerpt' => $excerpt]);
    wp_send_json_success($excerpt);
});

Define the key in wp-config.php (never in the plugin file, which might end up in a repo):

php
define('AI_EXCERPT_KEY', 'YOUR_KEY');

The button

Add a small admin script that calls admin-ajax.php?action=ai_excerpt with the post id and a nonce from wp_create_nonce('ai_excerpt'), and shows the result. Reload the editor to see the new excerpt.

Ideas

  • Generate SEO meta descriptions for your SEO plugin's field.
  • Suggest tags from content.
  • Translate posts into a second language as drafts.

Always review AI text before publishing.

Try it with one API key

Claude, GPT, Gemini, DeepSeek, image and video models through one OpenAI- and Anthropic-compatible endpoint. Prepaid, pay only for what you use.

Keep reading