How to Create an AI Image Generator Plugin for WordPress

Are you interested in enhancing your WordPress site with AI-powered image generation? In this tutorial, you’ll learn how to create a custom WordPress plugin that generates AI images using OpenAI’s DALL·E API. Let’s dive into the step-by-step process to build your very own AI Image Generator plugin.


Step 1: Understand the Plugin’s Purpose

This plugin will allow users to generate images by providing a text prompt. Users can include these images in their posts or pages using a shortcode. The plugin will also include a settings page for managing the API key required for OpenAI’s API.


Step 2: Set Up Your Development Environment

Before creating the plugin, ensure you have the following:

  • A local or online WordPress installation.
  • Access to the OpenAI API (sign up and obtain your API key).
  • A code editor like Visual Studio Code.

Step 3: Create the Plugin Skeleton

  1. Navigate to your WordPress installation’s wp-content/plugins directory.
  2. Create a folder named ai-image-generator.
  3. Inside this folder, create a PHP file called ai-image-generator.php.
  4. Open the file and add the following code:
<?php
/*
Plugin Name: AI Image Generator
Description: A plugin that generates AI images for WordPress content using OpenAI’s API.
Version: 1.0
Author: Your Name
*/

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

This basic header makes the plugin recognizable in WordPress.


Step 4: Add Plugin Settings for API Key

  1. Register a settings page to store the OpenAI API key.
  2. Add the following code to your plugin file:
// Register settings
function ai_image_generator_register_settings() {
    add_option( 'ai_image_generator_api_key', '' );
    register_setting( 'ai_image_generator_options_group', 'ai_image_generator_api_key' );
}
add_action( 'admin_init', 'ai_image_generator_register_settings' );

// Add admin menu
function ai_image_generator_register_options_page() {
    add_options_page(
        'AI Image Generator',
        'AI Image Generator',
        'manage_options',
        'ai-image-generator',
        'ai_image_generator_options_page'
    );
}
add_action( 'admin_menu', 'ai_image_generator_register_options_page' );

// Settings page HTML
function ai_image_generator_options_page() {
    ?>
    <div>
        <h1>AI Image Generator Settings</h1>
        <form method="post" action="options.php">
            <?php settings_fields( 'ai_image_generator_options_group' ); ?>
            <table>
                <tr valign="top">
                    <th scope="row"><label for="ai_image_generator_api_key">OpenAI API Key</label></th>
                    <td><input type="text" id="ai_image_generator_api_key" name="ai_image_generator_api_key" value="<?php echo esc_attr( get_option( 'ai_image_generator_api_key' ) ); ?>" style="width: 300px;" /></td>
                </tr>
            </table>
            <?php submit_button(); ?>
        </form>
    </div>
    <?php
}

Step 5: Add the AI Image Generation Functionality

  1. Use OpenAI’s API to generate images.
  2. Add the following code to your plugin:
// Generate AI image via shortcode
function ai_image_generator_generate_image( $atts, $content = null ) {
    $api_key = get_option( 'ai_image_generator_api_key' );
    if ( ! $api_key ) {
        return '<p>Please set your OpenAI API key in the settings page.</p>';
    }

    if ( ! $content ) {
        return '<p>Please provide a prompt for the AI image.</p>';
    }

    $response = wp_remote_post( 'https://api.openai.com/v1/images/generations', [
        'headers' => [
            'Authorization' => 'Bearer ' . $api_key,
            'Content-Type'  => 'application/json',
        ],
        'body'    => json_encode( [
            'prompt'         => $content,
            'n'              => 1,
            'size'           => '1024x1024',
        ] ),
    ] );

    if ( is_wp_error( $response ) ) {
        return '<p>Error generating image: ' . esc_html( $response->get_error_message() ) . '</p>';
    }

    $body = json_decode( wp_remote_retrieve_body( $response ), true );

    if ( isset( $body['data'][0]['url'] ) ) {
        return '<img src="' . esc_url( $body['data'][0]['url'] ) . '" alt="' . esc_attr( $content ) . '" style="max-width:100%; height:auto;" />';
    }

    return '<p>Failed to generate image. Please check your API key and try again.</p>';
}
add_shortcode( 'ai_image', 'ai_image_generator_generate_image' );

Step 6: Activate and Test the Plugin

  1. Go to Plugins > Installed Plugins in your WordPress admin panel.
  2. Find “AI Image Generator” and click Activate.
  3. Navigate to Settings > AI Image Generator and enter your OpenAI API key.
  4. Create or edit a post and use the shortcode [ai_image]Your prompt here[/ai_image] to generate an image.

Step 7: Extend and Customize

Here are some ideas to enhance your plugin:

  • Allow users to select image sizes (e.g., 256×256, 512×512, 1024×1024).
  • Store generated images in the WordPress media library.
  • Add a user-friendly interface for selecting prompts and settings.
Add a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Prev Next

Subscribe to My Newsletter

Subscribe to my email newsletter to get the latest posts delivered right to your email. Pure inspiration, zero spam.
You agree to the Terms of Use and Privacy Policy