'ainews_sanitize_auto_featured_image'));
register_setting('ainews_featured_image_options', 'ainews_image_generation_service', array('sanitize_callback' => 'ainews_sanitize_image_generation_service'));
register_setting('ainews_featured_image_options', 'ainews_image_style', array('sanitize_callback' => 'ainews_sanitize_image_style'));
register_setting('ainews_featured_image_options', 'ainews_image_dimensions', array('sanitize_callback' => 'ainews_sanitize_image_dimensions'));
}
/**
* Add featured image settings to the admin page
*/
function ainews_render_featured_image_settings() {
?>
🖼️ Featured Image Settings
'stabilityai/stable-diffusion-3-5-large',
'prompt' => $styled_prompt,
'image_size' => $siliconflow_size,
'n' => 1
);
error_log("AI News: SiliconFlow request body: " . json_encode($request_body));
error_log("AI News: Sending request to SiliconFlow API...");
$response = wp_remote_post('https://api.siliconflow.cn/v1/images/generations', array(
'headers' => array(
'Authorization' => 'Bearer ' . $api_key,
'Content-Type' => 'application/json'
),
'body' => json_encode($request_body),
'timeout' => 180
));
if (is_wp_error($response)) {
error_log('AI News: SiliconFlow API error - ' . $response->get_error_message());
return ainews_generate_placeholder_image($title, $language);
}
$status_code = wp_remote_retrieve_response_code($response);
$response_body = wp_remote_retrieve_body($response);
error_log("AI News: SiliconFlow API response code: {$status_code}");
error_log("AI News: SiliconFlow API response body: " . substr($response_body, 0, 500) . "...");
$data = json_decode($response_body, true);
if ($status_code !== 200) {
$error_message = isset($data['error']['message']) ? $data['error']['message'] : 'Unknown error';
error_log("AI News: SiliconFlow API returned error: {$error_message}");
return ainews_generate_placeholder_image($title, $language);
}
if (isset($data['data'][0]['url'])) {
$image_url = $data['data'][0]['url'];
error_log("AI News: SiliconFlow image generation successful: {$image_url}");
return $image_url;
} else {
error_log("AI News: SiliconFlow response does not contain image URL. Response structure: " . json_encode($data));
}
} catch (Exception $e) {
error_log('AI News: SiliconFlow generation error - ' . $e->getMessage());
}
error_log("AI News: SiliconFlow image generation failed, using placeholder");
return ainews_generate_placeholder_image($title, $language);
}
/**
* Generate image using OpenAI DALL-E API
*/
function ainews_generate_openai_image($title, $language = 'en') {
$api_key = get_option('ainews_openai_api_key', '');
if (empty($api_key)) {
return ainews_generate_placeholder_image($title, $language);
}
try {
// First optimize the prompt
$optimized_prompt = ainews_optimize_prompt_with_ai($title, $language);
$style = get_option('ainews_image_style', 'realistic');
$styled_prompt = $optimized_prompt . ', ' . $style . ' style, high quality, professional news image';
$response = wp_remote_post('https://api.openai.com/v1/images/generations', array(
'headers' => array(
'Authorization' => 'Bearer ' . $api_key,
'Content-Type' => 'application/json'
),
'body' => json_encode(array(
'model' => 'dall-e-3',
'prompt' => substr($styled_prompt, 0, 4000), // DALL-E has a prompt limit
'size' => '1024x1024',
'quality' => 'standard',
'n' => 1
)),
'timeout' => 60
));
if (is_wp_error($response)) {
error_log('AI News: OpenAI API error - ' . $response->get_error_message());
return ainews_generate_placeholder_image($title, $language);
}
$data = json_decode(wp_remote_retrieve_body($response), true);
if (isset($data['data'][0]['url'])) {
return $data['data'][0]['url'];
}
} catch (Exception $e) {
error_log('AI News: OpenAI generation error - ' . $e->getMessage());
}
return ainews_generate_placeholder_image($title, $language);
}
/**
* Generate image using DeepSeek API
*/
function ainews_generate_deepseek_image($title, $language = 'en') {
$api_key = get_option('ainews_deepseek_api_key', '');
if (empty($api_key)) {
return ainews_generate_placeholder_image($title, $language);
}
// DeepSeek doesn't have image generation API yet, use it for prompt optimization only
// Then fallback to SiliconFlow for actual generation
try {
$optimized_prompt = ainews_optimize_prompt_with_deepseek($title, $language);
// Use SiliconFlow with DeepSeek optimized prompt
$siliconflow_key = get_option('ainews_siliconflow_api_key', '');
if (!empty($siliconflow_key)) {
return ainews_generate_siliconflow_with_custom_prompt($optimized_prompt, $language);
}
} catch (Exception $e) {
error_log('AI News: DeepSeek optimization error - ' . $e->getMessage());
}
return ainews_generate_placeholder_image($title, $language);
}
/**
* Optimize prompt using AI (OpenAI GPT)
*/
function ainews_optimize_prompt_with_ai($title, $language = 'en') {
error_log("AI News: Starting prompt optimization with OpenAI for title: {$title}");
$openai_api_key = get_option('ainews_openai_api_key', '');
if (empty($openai_api_key)) {
error_log("AI News: OpenAI API key is empty, using basic prompt");
return ainews_create_basic_image_prompt($title, $language);
}
try {
$is_chinese = preg_match('/[\x{4e00}-\x{9fa5}]/u', $title);
error_log("AI News: Title language detection - Chinese: " . ($is_chinese ? 'YES' : 'NO'));
$system_prompt = "You are a helpful assistant that optimizes image generation prompts. Make the prompts more detailed and specific for news article featured images, while keeping the original meaning. Always respond in English.";
$user_prompt = $is_chinese
? "Please translate this Chinese news title to English and optimize it as an image generation prompt: \"{$title}\". Create a professional news image prompt with details about quality, style, and composition."
: "Please optimize this news title as an image generation prompt: \"{$title}\". Add details about quality, style, and composition for a professional news featured image.";
error_log("AI News: OpenAI user prompt: " . $user_prompt);
$request_body = array(
'model' => 'gpt-3.5-turbo',
'messages' => array(
array('role' => 'system', 'content' => $system_prompt),
array('role' => 'user', 'content' => $user_prompt)
),
'max_tokens' => 500,
'temperature' => 0.7
);
error_log("AI News: Sending request to OpenAI API for prompt optimization...");
$response = wp_remote_post('https://api.openai.com/v1/chat/completions', array(
'headers' => array(
'Authorization' => 'Bearer ' . $openai_api_key,
'Content-Type' => 'application/json'
),
'body' => json_encode($request_body),
'timeout' => 30
));
if (is_wp_error($response)) {
error_log('AI News: OpenAI API request error: ' . $response->get_error_message());
throw new Exception($response->get_error_message());
}
$status_code = wp_remote_retrieve_response_code($response);
$response_body = wp_remote_retrieve_body($response);
error_log("AI News: OpenAI API response code: {$status_code}");
if ($status_code !== 200) {
error_log("AI News: OpenAI API error response: " . substr($response_body, 0, 500));
throw new Exception("OpenAI API returned status code: {$status_code}");
}
$data = json_decode($response_body, true);
error_log("AI News: OpenAI API response received, parsing...");
if (isset($data['choices'][0]['message']['content'])) {
$optimized_prompt = trim($data['choices'][0]['message']['content']);
error_log("AI News: OpenAI prompt optimization successful: " . substr($optimized_prompt, 0, 150) . "...");
return $optimized_prompt;
} else {
error_log("AI News: OpenAI response does not contain expected content. Response: " . json_encode($data));
throw new Exception("Invalid response format from OpenAI");
}
} catch (Exception $e) {
error_log('AI News: Prompt optimization error - ' . $e->getMessage());
}
return ainews_create_basic_image_prompt($title, $language);
}
/**
* Optimize prompt using DeepSeek API
*/
function ainews_optimize_prompt_with_deepseek($title, $language = 'en') {
$api_key = get_option('ainews_deepseek_api_key', '');
if (empty($api_key)) {
return ainews_create_basic_image_prompt($title, $language);
}
try {
$is_chinese = preg_match('/[\x{4e00}-\x{9fa5}]/u', $title);
$user_prompt = $is_chinese
? "请将这个中文新闻标题翻译成英文并优化为图像生成提示词:\"{$title}\"。创建一个专业的新闻图像提示词,包含质量、风格和构图的细节。"
: "Please optimize this news title as an image generation prompt: \"{$title}\". Add details about quality, style, and composition for a professional news featured image.";
$response = wp_remote_post('https://api.deepseek.com/v1/chat/completions', array(
'headers' => array(
'Authorization' => 'Bearer ' . $api_key,
'Content-Type' => 'application/json'
),
'body' => json_encode(array(
'model' => 'deepseek-chat',
'messages' => array(
array('role' => 'user', 'content' => $user_prompt)
),
'max_tokens' => 500,
'temperature' => 0.7
)),
'timeout' => 30
));
if (is_wp_error($response)) {
throw new Exception($response->get_error_message());
}
$data = json_decode(wp_remote_retrieve_body($response), true);
if (isset($data['choices'][0]['message']['content'])) {
return $data['choices'][0]['message']['content'];
}
} catch (Exception $e) {
error_log('AI News: DeepSeek optimization error - ' . $e->getMessage());
}
return ainews_create_basic_image_prompt($title, $language);
}
/**
* Generate SiliconFlow image with custom prompt
*/
function ainews_generate_siliconflow_with_custom_prompt($prompt, $language = 'en') {
$api_key = get_option('ainews_siliconflow_api_key', '');
if (empty($api_key)) {
return ainews_generate_placeholder_image($prompt, $language);
}
try {
$dimensions = get_option('ainews_image_dimensions', '1200x630');
$style = get_option('ainews_image_style', 'realistic');
// Add style to prompt
$styled_prompt = $prompt . ', style: ' . $style . ', high quality, detailed, professional';
$response = wp_remote_post('https://api.siliconflow.cn/v1/images/generations', array(
'headers' => array(
'Authorization' => 'Bearer ' . $api_key,
'Content-Type' => 'application/json'
),
'body' => json_encode(array(
'model' => 'stabilityai/stable-diffusion-3-5-large',
'prompt' => $styled_prompt,
'image_size' => $dimensions,
'n' => 1
)),
'timeout' => 180
));
if (is_wp_error($response)) {
error_log('AI News: SiliconFlow API error - ' . $response->get_error_message());
return ainews_generate_placeholder_image($prompt, $language);
}
$data = json_decode(wp_remote_retrieve_body($response), true);
if (isset($data['data'][0]['url'])) {
return $data['data'][0]['url'];
}
} catch (Exception $e) {
error_log('AI News: SiliconFlow generation error - ' . $e->getMessage());
}
return ainews_generate_placeholder_image($prompt, $language);
}
/**
* Create basic image prompt without AI optimization
*/
function ainews_create_basic_image_prompt($title, $language = 'en') {
$style = get_option('ainews_image_style', 'realistic');
if ($language === 'zh') {
return "Professional news image about: {$title}, {$style} style, high quality, 4k, detailed, news photography";
} else {
return "{$title}, {$style} style, high quality, 4k, detailed, professional news image, clean composition";
}
}
/**
* Generate placeholder image using local WordPress functionality
*/
function ainews_generate_placeholder_image($title, $language = 'en') {
$dimensions = get_option('ainews_image_dimensions', '1200x630');
$style = get_option('ainews_image_style', 'news');
$width = 1200;
$height = 630;
if ($dimensions !== 'custom') {
list($width, $height) = explode('x', $dimensions);
}
// Create a simple placeholder using WordPress default image
// Use WordPress's built-in placeholder functionality
$placeholder_url = ainews_get_default_placeholder_image($width, $height, $title);
return $placeholder_url;
}
/**
* Get default placeholder image using WordPress functionality
*/
function ainews_get_default_placeholder_image($width, $height, $title) {
// Use WordPress's built-in placeholder image
// This creates a simple colored rectangle with text
$upload_dir = wp_upload_dir();
$placeholder_dir = $upload_dir['basedir'] . '/ainews-placeholders';
// Create directory if it doesn't exist
if (!file_exists($placeholder_dir)) {
wp_mkdir_p($placeholder_dir);
}
// Generate filename based on dimensions and title hash
$filename = 'placeholder-' . $width . 'x' . $height . '-' . md5($title) . '.jpg';
$file_path = $placeholder_dir . '/' . $filename;
$file_url = $upload_dir['baseurl'] . '/ainews-placeholders/' . $filename;
// Check if file already exists
if (file_exists($file_path)) {
return $file_url;
}
// Create a simple placeholder image using GD library
if (function_exists('imagecreate')) {
$image = imagecreate($width, $height);
// Define colors
$bg_color = imagecolorallocate($image, 0, 115, 170); // Blue background
$text_color = imagecolorallocate($image, 255, 255, 255); // White text
// Fill background
imagefill($image, 0, 0, $bg_color);
// Add text (simplified version)
$text = substr($title, 0, 30); // Limit text length
$font_size = min($width / 20, $height / 10, 24); // Responsive font size
// Calculate text position (centered)
$text_width = strlen($text) * $font_size * 0.6; // Approximate width
$text_height = $font_size;
$x = ($width - $text_width) / 2;
$y = ($height + $text_height) / 2;
// Add text to image
imagestring($image, 5, $x, $y, $text, $text_color);
// Save image
imagejpeg($image, $file_path, 90);
imagedestroy($image);
return $file_url;
}
// Fallback: return a simple data URI placeholder
return ainews_create_data_uri_placeholder($width, $height, $title);
}
/**
* Create a simple data URI placeholder as fallback
*/
function ainews_create_data_uri_placeholder($width, $height, $title) {
// Create a simple SVG placeholder
$text = substr($title, 0, 30);
$svg = '
' . esc_html($text) . '
';
return 'data:image/svg+xml;base64,' . base64_encode($svg);
}
/**
* Generate image using Unsplash API
*/
function ainews_generate_unsplash_image($title, $language = 'en') {
$unsplash_access_key = get_option('ainews_unsplash_access_key', '');
if (empty($unsplash_access_key)) {
// Fallback to placeholder
return ainews_generate_placeholder_image($title, $language);
}
// Search for relevant images
$query = urlencode($title);
$url = "https://api.unsplash.com/search/photos?query={$query}&per_page=1&orientation=landscape";
$response = wp_remote_get($url, array(
'headers' => array(
'Authorization' => 'Client-ID ' . $unsplash_access_key
)
));
if (is_wp_error($response)) {
return ainews_generate_placeholder_image($title, $language);
}
$data = json_decode(wp_remote_retrieve_body($response), true);
if (isset($data['results'][0]['urls']['regular'])) {
return $data['results'][0]['urls']['regular'];
}
return ainews_generate_placeholder_image($title, $language);
}
/**
* Generate image using Pixabay API
*/
function ainews_generate_pixabay_image($title, $language = 'en') {
$pixabay_api_key = get_option('ainews_pixabay_api_key', '');
if (empty($pixabay_api_key)) {
// Fallback to placeholder
return ainews_generate_placeholder_image($title, $language);
}
// Search for relevant images
$query = urlencode($title);
$url = "https://pixabay.com/api/?key={$pixabay_api_key}&q={$query}&image_type=photo&orientation=horizontal&per_page=1";
$response = wp_remote_get($url);
if (is_wp_error($response)) {
return ainews_generate_placeholder_image($title, $language);
}
$data = json_decode(wp_remote_retrieve_body($response), true);
if (isset($data['hits'][0]['webformatURL'])) {
return $data['hits'][0]['webformatURL'];
}
return ainews_generate_placeholder_image($title, $language);
}
/**
* Generate custom image (placeholder for future implementation)
*/
function ainews_generate_custom_image($title, $language = 'en') {
// This can be extended to use other AI image generation services
// like DALL-E, Midjourney API, or custom implementations
return ainews_generate_placeholder_image($title, $language);
}
/**
* Download and attach image to post
*/
function ainews_attach_image_to_post($post_id, $image_url, $title) {
error_log("AI News: Starting image download from: {$image_url}");
// Download the image using wp_remote_get for better error handling
$response = wp_remote_get($image_url, array(
'timeout' => 60,
'headers' => array(
'User-Agent' => 'WordPress/AI-News-Plugin'
)
));
if (is_wp_error($response)) {
error_log("AI News: Failed to download image: " . $response->get_error_message());
return false;
}
$image_data = wp_remote_retrieve_body($response);
if (empty($image_data)) {
error_log("AI News: Empty image data received");
return false;
}
error_log("AI News: Downloaded image data size: " . strlen($image_data) . " bytes");
// Generate a unique filename
$filename = 'ainews-featured-' . $post_id . '-' . time() . '.jpg';
// Upload the image
$upload = wp_upload_bits($filename, null, $image_data);
if ($upload['error']) {
error_log("AI News: Upload error: " . $upload['error']);
return false;
}
error_log("AI News: Image uploaded to: " . $upload['file']);
// Get file type
$wp_filetype = wp_check_filetype($upload['file'], null);
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($title . ' - Featured Image'),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment
$attachment_id = wp_insert_attachment($attachment, $upload['file'], $post_id);
if (is_wp_error($attachment_id)) {
error_log("AI News: Failed to insert attachment: " . $attachment_id->get_error_message());
return false;
}
error_log("AI News: Attachment created with ID: {$attachment_id}");
// Generate attachment metadata
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata($attachment_id, $upload['file']);
wp_update_attachment_metadata($attachment_id, $attachment_data);
error_log("AI News: Attachment metadata generated successfully");
return $attachment_id;
}
/**
* Add additional settings fields for API keys
*/
function ainews_render_api_key_settings() {
?>
🔑 AI Image Service API Keys
'ainews_sanitize_openai_api_key'));
register_setting('ainews_featured_image_options', 'ainews_siliconflow_api_key', array('sanitize_callback' => 'ainews_sanitize_siliconflow_api_key'));
register_setting('ainews_featured_image_options', 'ainews_deepseek_api_key', array('sanitize_callback' => 'ainews_sanitize_deepseek_api_key'));
register_setting('ainews_featured_image_options', 'ainews_unsplash_access_key', array('sanitize_callback' => 'ainews_sanitize_unsplash_access_key'));
register_setting('ainews_featured_image_options', 'ainews_pixabay_api_key', array('sanitize_callback' => 'ainews_sanitize_pixabay_api_key'));
}
add_action('admin_init', 'ainews_register_image_settings');
/**
* Add settings to activation hook
*/
function ainews_featured_image_activate() {
add_option('ainews_auto_featured_image', false);
add_option('ainews_image_generation_service', 'siliconflow');
add_option('ainews_image_style', 'realistic');
add_option('ainews_image_dimensions', '1200x630');
add_option('ainews_openai_api_key', '');
add_option('ainews_siliconflow_api_key', '');
add_option('ainews_deepseek_api_key', '');
add_option('ainews_unsplash_access_key', '');
add_option('ainews_pixabay_api_key', '');
}
register_activation_hook(__FILE__, 'ainews_featured_image_activate');
/**
* Clean up on deactivation
*/
function ainews_featured_image_deactivate() {
// Keep the options, just clean up any temporary data
}
register_deactivation_hook(__FILE__, 'ainews_featured_image_deactivate');
/**
* Manual test function for debugging
* Add this to the admin area for testing
*/
function ainews_test_featured_image_generation() {
if (!current_user_can('manage_options')) {
return;
}
// Test with a sample post
$test_title = "AI Technology Breakthrough in 2024";
$test_content = "This is a test article about AI technology.";
$test_language = "en";
error_log("AI News: Starting manual test of featured image generation");
// Create a test post
$test_post = array(
'post_title' => $test_title,
'post_content' => $test_content,
'post_status' => 'draft',
'post_type' => 'post'
);
$test_post_id = wp_insert_post($test_post);
if ($test_post_id) {
error_log("AI News: Test post created with ID: {$test_post_id}");
// Try to generate featured image
$result = ainews_auto_set_featured_image($test_post_id, $test_title, $test_content, $test_language);
if ($result) {
error_log("AI News: Test successful! Featured image set with attachment ID: {$result}");
echo 'Featured image test successful! Check post ID: ' . esc_html($test_post_id) . '
';
} else {
error_log("AI News: Test failed - no featured image generated");
echo 'Featured image test failed. Check error logs for details.
';
}
} else {
error_log("AI News: Failed to create test post");
echo 'Failed to create test post.
';
}
}
/**
* Convert WordPress dimensions to SiliconFlow supported format
*/
function ainews_convert_to_siliconflow_size($dimensions) {
// SiliconFlow supported sizes for Stable Diffusion 3.5
$supported_sizes = array(
'1024x1024', '1152x896', '1216x832', '1344x768', '1536x640',
'640x1536', '768x1344', '832x1216', '896x1152'
);
// If the dimension is already supported, use it
if (in_array($dimensions, $supported_sizes)) {
return $dimensions;
}
// Parse the input dimensions
$parts = explode('x', $dimensions);
if (count($parts) !== 2) {
return '1024x1024'; // Default fallback
}
$width = intval($parts[0]);
$height = intval($parts[1]);
$ratio = $width / $height;
// Find the best matching supported size based on aspect ratio
$best_match = '1024x1024';
$best_ratio_diff = PHP_FLOAT_MAX;
foreach ($supported_sizes as $size) {
$size_parts = explode('x', $size);
$size_width = intval($size_parts[0]);
$size_height = intval($size_parts[1]);
$size_ratio = $size_width / $size_height;
$ratio_diff = abs($ratio - $size_ratio);
if ($ratio_diff < $best_ratio_diff) {
$best_ratio_diff = $ratio_diff;
$best_match = $size;
}
}
return $best_match;
}
// Sanitization callback functions for register_setting
function ainews_sanitize_auto_featured_image($input) {
return (bool) $input;
}
function ainews_sanitize_image_generation_service($input) {
$allowed_values = array('siliconflow', 'placeholder', 'openai', 'deepseek', 'unsplash', 'pixabay');
return in_array($input, $allowed_values) ? $input : 'siliconflow';
}
function ainews_sanitize_image_style($input) {
$allowed_values = array('news', 'modern', 'creative', 'minimal');
return in_array($input, $allowed_values) ? $input : 'news';
}
function ainews_sanitize_image_dimensions($input) {
return sanitize_text_field($input);
}
function ainews_sanitize_openai_api_key($input) {
return sanitize_text_field($input);
}
function ainews_sanitize_siliconflow_api_key($input) {
return sanitize_text_field($input);
}
function ainews_sanitize_deepseek_api_key($input) {
return sanitize_text_field($input);
}
function ainews_sanitize_unsplash_access_key($input) {
return sanitize_text_field($input);
}
function ainews_sanitize_pixabay_api_key($input) {
return sanitize_text_field($input);
}