How to Create an AI Text Generator Plugin for WordPress in 4 Easy Steps – 2023

Today we’re going to add some AI magic to your website. We’ll be creating a simple WordPress plugin that uses the OpenAI API to generate text from a prompt. It’s simpler than it sounds, I promise. Let’s get started!

Step 1: Set Up Your Workspace

First, we’re going to set up the space where we will create our plugin. Create a new folder named ai-text-generator in the wp-content/plugins directory of your WordPress installation.

Inside this folder, create two files: ai-text-generator.php and admin-page.php. The ai-text-generator.php file will be the main plugin file, and the admin-page.php file will control the display of our plugin’s admin page.

Step 2: Register the Plugin

Open the ai-text-generator.php file and let’s register our plugin with the following code:

 
				
					<?php
/**
 * Plugin Name: AI Text Generator
 */

if (!defined('ABSPATH')) {
    exit;
}

require_once plugin_dir_path(__FILE__) . 'admin-page.php';

function load_ai_text_generator() {
    new AI_Text_Generator_Admin_Page();
}
add_action('plugins_loaded', 'load_ai_text_generator');

				
			

This code gives our plugin a name, and includes the admin-page.php file. It also adds a hook to load our admin page when all plugins are loaded.

Step 3: Create the Admin Page

Open the admin-page.php file. This is where we’ll set up an interface for users to enter a prompt and see the AI’s response. Let’s start with the basic layout:

				
					<?php
class AI_Text_Generator_Admin_Page {

    public function __construct() {
        add_action('admin_menu', array($this, 'create_menu'));
    }

    public function create_menu() {
        add_menu_page('AI Text Generator', 'AI Text Generator', 'manage_options', 'ai-text-generator', array($this, 'display_page'));
    }

    public function display_page() {
        ?>
        <h1>AI Text Generator</h1>
        <form method="POST">
            <label for="prompt">Prompt:</label>
            <input type="text" id="prompt" name="prompt">
            <button type="submit" name="submit">Generate Text</button>
        </form>
        <?php
        if (isset($_POST['submit']) && !empty($_POST['prompt'])) {
            $this->generate_text($_POST['prompt']);
        }
    }

    private function generate_text($prompt) {
        // Call OpenAI API here...
    }
}

				
			

With this code, we’ve set up a simple page with a form where users can enter a prompt. When the form is submitted, the generate_text() function is called with the prompt as an argument. This is where we’ll call the OpenAI API.

Step 4: Connect to OpenAI API

To connect to the OpenAI API, we’ll use the PHP curl function. Replace // Call OpenAI API here... in the generate_text() function with the following code:

				
					$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/engines/davinci-codex/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['prompt' => $prompt, 'max_tokens' => 60]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer YOUR_OPENAI_API_KEY'
]);

$output = curl_exec($ch);

curl_close($ch);

$response = json_decode($output, true);

echo '<p>' . $response['choices'][0]['text'] . '</p>';

				
			

Replace 'YOUR_OPENAI_API_KEY' with your actual OpenAI API key. This code sends a POST request to the OpenAI API with the prompt and a limit of 60 tokens. It then displays the generated text on the page.

And voila! You’ve just created a basic AI text generator plugin for WordPress! Just go to your WordPress dashboard, navigate to the Plugins section, and activate your plugin. Then, you can access the AI Text Generator from the WordPress dashboard menu.

The final plugin code is as follows:

				
					// ai-text-generator.php
<?php
/**
 * Plugin Name: AI Text Generator
 */

if (!defined('ABSPATH')) {
    exit;
}

require_once plugin_dir_path(__FILE__) . 'admin-page.php';

function load_ai_text_generator() {
    new AI_Text_Generator_Admin_Page();
}
add_action('plugins_loaded', 'load_ai_text_generator');

// admin-page.php
<?php
class AI_Text_Generator_Admin_Page {

    public function __construct() {
        add_action('admin_menu', array($this, 'create_menu'));
    }

    public function create_menu() {
        add_menu_page('AI Text Generator', 'AI Text Generator', 'manage_options', 'ai-text-generator', array($this, 'display_page'));
    }

    public function display_page() {
        ?>
        <h1>AI Text Generator</h1>
        <form method="POST">
            <label for="prompt">Prompt:</label>
            <input type="text" id="prompt" name="prompt">
            <button type="submit" name="submit">Generate Text</button>
        </form>
        <?php
        if (isset($_POST['submit']) && !empty($_POST['prompt'])) {
            $this->generate_text($_POST['prompt']);
        }
    }

    private function generate_text($prompt) {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/engines/davinci-codex/completions');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['prompt' => $prompt, 'max_tokens' => 60]));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Authorization: Bearer YOUR_OPENAI_API_KEY'
        ]);

        $output = curl_exec($ch);

        curl_close($ch);

        $response = json_decode($output, true);

        echo '<p>' . $response['choices'][0]['text'] . '</p>';
    }
}

				
			

Remember, the key to learning is practice, so keep playing around with this and see what else you can create. Until next time, happy coding!

Table of Contents

Pro Feature

When to Use This Feature

Use Examples