oai_featured_img.php

CodeWP Featured Image Generator

This WordPress plugin leverages OpenAI's Dalle 3 AI to automatically generate featured images for posts. It adds a button to the post editor screen that, when clicked, sends a request to generate an image based on the post's content.

<?php /** * Plugin Name: CodeWP Featured Image Generator * Description: Generates featured images for posts using OpenAI's Dalle 3 AI. * Version: 1.0 * Author: CodeWP * Text Domain: cwpai-featured-image-generator */ // If this file is called directly, abort. if ( ! defined( 'WPINC' ) ) { die; } function cwpai_enqueue_scripts($hook) { // Check if we are on post.php or post-new.php on the admin side if (!in_array($hook, ['post.php', 'post-new.php'], true)) { return; } // Inline JavaScript ?> <script type='text/javascript'> document.addEventListener('DOMContentLoaded', function() { const generateBtn = document.getElementById('cwpai_generate_btn'); if (generateBtn) { generateBtn.addEventListener('click', function(e) { e.preventDefault(); const postId = generateBtn.dataset.postid; // Update button to show loading state generateBtn.textContent = 'Generating...'; generateBtn.disabled = true; // Call WordPress REST API to generate the image wp.apiRequest({ path: '/cwpai/v1/generate-image/' + postId, method: 'POST' }).then(function(response) { if(response.success) { alert('Featured Image Generated Successfully!'); location.reload(); } else { alert('Error: ' + (response.data.message || 'Something went wrong')); } }).catch(function(error) { alert('Request failed: ' + error.message); }).finally(function() { // Reset button after operation generateBtn.textContent = 'Generate Image'; generateBtn.disabled = false; }); }); } }); </script> <?php } add_action('admin_enqueue_scripts', 'cwpai_enqueue_scripts'); function cwpai_register_meta_box() { add_meta_box( 'cwpai_featured_image_generator', __('Generate Featured Image', 'cwpai-featured-image-generator'), 'cwpai_display_generator_button', null, 'side', 'high' ); } add_action('add_meta_boxes', 'cwpai_register_meta_box'); function cwpai_display_generator_button($post) { echo '<button type="button" id="cwpai_generate_btn" data-postid="'. esc_attr($post->ID) .'" class="button button-primary button-large">'.__('Generate Image', 'cwpai-featured-image-generator').'</button>'; } // Register REST API endpoint function cwpai_register_rest_route() { register_rest_route('cwpai/v1', '/generate-image/(?P<id>\d+)', [ 'methods' => 'POST', 'callback' => 'cwpai_handle_generate_image', 'permission_callback' => 'cwpai_check_permissions', 'args' => [ 'id' => [ 'required' => true, 'validate_callback' => function($param, $request, $key) { return is_numeric($param); } ], ], ]); } add_action('rest_api_init', 'cwpai_register_rest_route'); function cwpai_check_permissions(WP_REST_Request $request) { return current_user_can('edit_post', $request['id']); } function cwpai_handle_generate_image(WP_REST_Request $request) { $post_id = $request['id']; $post_data = get_post($post_id); $excerpt = !empty($post_data->post_excerpt) ? $post_data->post_excerpt : wp_trim_words($post_data->post_content, 100); $api_key = defined('OPENAI_API_KEY') ? OPENAI_API_KEY : ''; // Placeholder: Should retrieve API key securely, e.g. from WP options. if ( empty($api_key) ) { return new WP_Error('missing_api_key', __('Missing OpenAI API key.', 'cwpai-featured-image-generator')); } // Generate image prompt using OpenAI chat completions $prompt_response = wp_remote_post( 'https://api.openai.com/v1/chat/completions', [ 'headers' => [ 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $api_key, ], 'body' => json_encode([ 'model' => 'gpt-3.5-turbo', 'messages' => [ [ 'role' => 'system', 'content' => 'Based on the user’s input, you must generate a single sentence, detailed prompt to generate an image using an AI image generation. The image is the thumbnail for the blog post, and the content the user passes in is portions of that blog post. Distill a single concept or topic based on the user’s input, then create the prompt for image generation.' ], [ 'role' => 'user', 'content' => sanitize_text_field($excerpt), ], ], ]), 'timeout' => 60, ] ); if (is_wp_error($prompt_response) || wp_remote_retrieve_response_code($prompt_response) !== 200) { return new WP_Error('api_error', __('Error communicating with OpenAI API.', 'cwpai-featured-image-generator')); } $prompt_data = json_decode(wp_remote_retrieve_body($prompt_response), true); $prompt = $prompt_data['choices'][0]['message']['content'] ?? ''; if (empty($prompt)) { return new WP_Error('prompt_error', __('Unable to generate image prompt.', 'cwpai-featured-image-generator')); } // Generate image using Dalle 3 API $image_response = wp_remote_post( 'https://api.openai.com/v1/images/generations', [ 'headers' => [ 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $api_key, ], 'body' => json_encode([ 'model' => 'dall-e-3', 'prompt' => sanitize_text_field($prompt), 'n' => 1, 'size' => '1792x1024', ]), 'timeout' => 60, ] ); if (is_wp_error($image_response) || wp_remote_retrieve_response_code($image_response) !== 200) { return new WP_Error('api_error', __('Error generating image with Dalle 3 API.', 'cwpai-featured-image-generator')); } $image_data = json_decode(wp_remote_retrieve_body($image_response), true); $image_url = $image_data['data'][0]['url'] ?? ''; if (empty($image_url)) { return new WP_Error('image_error', __('Unable to get image URL.', 'cwpai-featured-image-generator')); } // Upload image to media library and set as featured image $image_id = cwpai_upload_image_to_media_library($image_url, $post_id); if (is_wp_error($image_id)) { return $image_id; } set_post_thumbnail($post_id, $image_id); return rest_ensure_response(['success' => true]); } function cwpai_upload_image_to_media_library($image_url, $post_id) { require_once(ABSPATH . 'wp-admin/includes/file.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); require_once(ABSPATH . 'wp-admin/includes/image.php'); add_filter('upload_mimes', 'cwpai_custom_upload_mimes'); $tmp = cwpai_custom_download_image($image_url); if (is_wp_error($tmp)) { return $tmp; } // Extract the file extension directly from the URL $file_ext = pathinfo(parse_url($image_url, PHP_URL_PATH), PATHINFO_EXTENSION); $file_name = sanitize_file_name($post_id . '-' . time() . '.' . $file_ext); $file_array = [ 'name' => $file_name, 'tmp_name' => $tmp, ]; $id = media_handle_sideload($file_array, $post_id, __('Generated featured image', 'cwpai-featured-image-generator')); if (is_wp_error($id)) { @unlink($file_array['tmp_name']); return $id; } return $id; } function cwpai_custom_upload_mimes($mimes) { $mimes['png'] = 'image/png'; return $mimes; } function cwpai_custom_download_image($image_url) { $ch = curl_init($image_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); $data = curl_exec($ch); curl_close($ch); if ($data === false) { return new WP_Error('download_error', __('Error downloading image.', 'cwpai-featured-image-generator')); } // Create a temporary file with the correct extension $file_ext = pathinfo(parse_url($image_url, PHP_URL_PATH), PATHINFO_EXTENSION); $tmp_fname = tempnam(sys_get_temp_dir(), 'cwpai_') . '.' . $file_ext; file_put_contents($tmp_fname, $data); return $tmp_fname; }

Frequently Asked Questions

The plugin automatically generates featured images for WordPress posts by using OpenAI's Dalle 3 AI upon clicking a button in the post editor.