prefix . 'ainews_history'; // Check if table exists // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) { $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE $table_name ( id mediumint(9) NOT NULL AUTO_INCREMENT, created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL, topic varchar(255) NOT NULL, title text NOT NULL, post_id bigint(20) UNSIGNED NOT NULL, language varchar(10) DEFAULT 'en' NOT NULL, PRIMARY KEY (id), KEY post_id (post_id), KEY created_at (created_at) ) $charset_collate;"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); } } // Add admin menu add_action('admin_menu', 'ainews_admin_menu'); function ainews_admin_menu() { // Get custom logo data URI $logo_svg = ainews_get_logo_data_uri(); add_menu_page( 'AI News', 'AI News', 'manage_options', 'ainews', 'ainews_admin_page', $logo_svg, 30 ); } // Get custom logo as data URI function ainews_get_logo_data_uri() { $logo_file = AINEWS_PLUGIN_DIR . 'logo.svg'; if (file_exists($logo_file)) { $svg_content = file_get_contents($logo_file); // Clean up the SVG for data URI usage - remove animations for menu icon $svg_content = preg_replace('/]*>.*?<\/animate>/s', '', $svg_content); $svg_content = preg_replace('/]*\/>/', '', $svg_content); // Encode for data URI $svg_encoded = 'data:image/svg+xml;base64,' . base64_encode($svg_content); return $svg_encoded; } // Fallback to default icon if logo file doesn't exist return 'dashicons-rss'; } // Enqueue admin styles add_action('admin_enqueue_scripts', 'ainews_admin_scripts'); function ainews_admin_scripts($hook) { if ($hook !== 'toplevel_page_ainews') { return; } // Enqueue jQuery wp_enqueue_script('jquery'); // Enqueue our custom admin CSS wp_enqueue_style( 'ainews-admin-css', AINEWS_PLUGIN_URL . 'assets/css/admin.css', array(), AINEWS_VERSION ); // Enqueue our custom admin JS wp_enqueue_script( 'ainews-admin-js', AINEWS_PLUGIN_URL . 'assets/js/admin.js', array('jquery'), AINEWS_VERSION, true ); // Localize script for AJAX wp_localize_script('ainews-admin-js', 'ainews_ajax', array( 'ajaxurl' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('ainews_nonce') )); } // Admin page function ainews_admin_page() { $tab = isset($_GET['tab']) ? sanitize_key($_GET['tab']) : 'generate'; ?>

AI News Generater by Ausdata Science

Plugin Settings saved successfully!

'; } ?>
'font-size: 13px; padding: 6px 12px;')); ?>

🔧 Basic Settings

📝 Post Settings

✏️ Prompt Management

📰 News Topics

Select topics for article generation:

⚙️ Select Generation Mode

🚀 Manual Generation Controls

Generate articles immediately with complete control. Click the button below to create one article using your current settings.

⏰ Auto Generation Controls

Configure automatic article generation on a schedule. When active, manual generation is disabled to prevent conflicts.

⚙️ Auto Generation Settings

'Save Auto Settings', 'style' => 'font-size: 13px; padding: 6px 12px;')); ?>

Changes will apply to the next scheduled generation

💡 Usage Information

🎯 Generation Modes

Choose between Manual or Auto generation. Only one mode can be active at a time. Switching modes will stop the current operation.

  • Manual Mode: Auto generation is stopped. Each click generates exactly one article.
  • Auto Mode: Manual generation is disabled while auto mode is active. Switch to Manual Mode to generate articles on demand.

⚙️ Setup Tips

  • API Key: Configure your Gemini API key in Plugin Settings first.
  • Topics: Select preferred news topics in Plugin Settings.
  • Content Review: Generated articles use your default post status.
  • Prompts: Customize AI prompts to match your content style.

Featured Image Settings saved successfully!

'; } ?>
prefix . 'ainews_history'; // Check if table exists // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") == $table_name; // Handle clear history action if (isset($_POST['action']) && sanitize_text_field($_POST['action']) === 'clear_history' && current_user_can('manage_options')) { check_admin_referer('ainews_clear_history_nonce'); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->query("TRUNCATE TABLE $table_name"); echo '

History cleared successfully.

'; } // Handle delete single record action if (isset($_POST['action']) && sanitize_text_field($_POST['action']) === 'delete_record' && current_user_can('manage_options')) { check_admin_referer('ainews_delete_record_nonce'); $record_id = intval($_POST['record_id']); if ($record_id > 0) { $deleted = $wpdb->delete($table_name, ['id' => $record_id], ['%d']); if ($deleted) { echo '

History record deleted successfully.

'; } else { echo '

Failed to delete history record.

'; } } } // Get history records // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching $history = $table_exists ? $wpdb->get_results("SELECT * FROM $table_name ORDER BY created_at DESC LIMIT 100") : []; ?>

📊 History Management

Manage your article generation history. You can view all generated articles and clear records when needed.

post_id); $post_exists = $post && $post->post_status !== 'trash'; ?>
Date & Time Topic Generated Title Status Actions

No generation history found.

Start generating articles to see your history here.

created_at)); ?> topic); ?> title); ?> ✅ post_status)); ?> ❌ Deleted
Edit post_status === 'publish') : ?> View Post Deleted
= 100) : ?>

Showing the latest 100 records. Older records are still preserved.

'ainews_sanitize_api_key')); register_setting('ainews_options', 'ainews_post_category', array('sanitize_callback' => 'ainews_sanitize_post_category')); register_setting('ainews_options', 'ainews_schedule_interval', array('sanitize_callback' => 'ainews_sanitize_schedule_interval')); register_setting('ainews_options', 'ainews_article_count', array('sanitize_callback' => 'ainews_sanitize_article_count')); register_setting('ainews_options', 'ainews_language', array('sanitize_callback' => 'ainews_sanitize_language')); register_setting('ainews_options', 'ainews_selected_topics', array('sanitize_callback' => 'ainews_sanitize_selected_topics')); register_setting('ainews_options', 'ainews_post_status', array('sanitize_callback' => 'ainews_sanitize_post_status')); register_setting('ainews_options', 'ainews_prompt_type', array('sanitize_callback' => 'ainews_sanitize_prompt_type')); register_setting('ainews_options', 'ainews_prompt_language', array('sanitize_callback' => 'ainews_sanitize_prompt_language')); register_setting('ainews_options', 'ainews_custom_interval', array('sanitize_callback' => 'ainews_sanitize_custom_interval')); // Handle Generate Articles tab form submissions only on our admin page if (isset($_POST['action']) && current_user_can('manage_options') && isset($_GET['page']) && sanitize_text_field($_GET['page']) === 'ainews') { // Only check our custom nonce for Generate Articles tab actions $generate_tab_actions = ['Save Schedule Settings', 'Pause Auto Generation', 'Resume Auto Generation', 'Save Auto Settings']; if (in_array(sanitize_text_field($_POST['action']), $generate_tab_actions)) { check_admin_referer('ainews_nonce'); } if (sanitize_text_field($_POST['action']) === 'Save Schedule Settings') { // Verify nonce for this action if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'ainews_nonce')) { wp_die(esc_html__('Security check failed. Please try again.', 'ai-news')); } // Save schedule settings $schedule_interval = sanitize_text_field($_POST['schedule_interval'] ?? 'manual'); $article_count = absint($_POST['article_count'] ?? 1); $custom_interval = absint($_POST['custom_interval'] ?? 60); // Validate custom interval if ($custom_interval < 1 || $custom_interval > 10080) { $custom_interval = 60; } update_option('ainews_schedule_interval', $schedule_interval); update_option('ainews_article_count', $article_count); update_option('ainews_custom_interval', $custom_interval); // Update scheduled events wp_clear_scheduled_hook('ainews_generate_articles'); if ($schedule_interval !== 'manual') { $interval_key = ($schedule_interval === 'custom') ? 'ainews_custom' : $schedule_interval; wp_schedule_event(time(), $interval_key, 'ainews_generate_articles'); update_option('ainews_schedule_paused', false); } add_action('admin_notices', function() { echo '

Schedule settings saved successfully!

'; }); } elseif (sanitize_text_field($_POST['action']) === 'Pause Auto Generation') { // Verify nonce for this action if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'ainews_nonce')) { wp_die(esc_html__('Security check failed. Please try again.', 'ai-news')); } update_option('ainews_schedule_paused', true); add_action('admin_notices', function() { echo '

Auto generation paused.

'; }); } elseif (sanitize_text_field($_POST['action']) === 'Resume Auto Generation') { // Verify nonce for this action if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'ainews_nonce')) { wp_die(esc_html__('Security check failed. Please try again.', 'ai-news')); } update_option('ainews_schedule_paused', false); add_action('admin_notices', function() { echo '

Auto generation resumed.

'; }); } elseif (sanitize_text_field($_POST['action']) === 'Save Auto Settings') { // Add nonce check for this specific action check_admin_referer('ainews_save_auto_settings_action', 'ainews_auto_settings_nonce'); // Save auto generation settings $schedule_interval = sanitize_text_field($_POST['schedule_interval'] ?? 'daily'); $article_count = absint($_POST['article_count'] ?? 1); $custom_interval = absint($_POST['custom_interval'] ?? 60); // Validate custom interval if ($custom_interval < 1 || $custom_interval > 10080) { $custom_interval = 60; } // Save the settings update_option('ainews_schedule_interval', $schedule_interval); update_option('ainews_article_count', $article_count); update_option('ainews_custom_interval', $custom_interval); update_option('ainews_last_auto_interval', $schedule_interval); // Update scheduled events only if auto mode is currently enabled if (get_option('ainews_schedule_interval') !== 'manual' && get_option('ainews_auto_enabled', false)) { // Only schedule if not already scheduled if (!wp_next_scheduled('ainews_generate_articles')) { $interval_key = ($schedule_interval === 'custom') ? 'ainews_custom' : $schedule_interval; wp_schedule_event(time() + 60, $interval_key, 'ainews_generate_articles'); } } add_action('admin_notices', function() { echo '

Auto generation settings saved successfully!

'; }); } } } // Add custom cron schedules add_filter('cron_schedules', 'ainews_add_cron_schedule'); function ainews_add_cron_schedule($schedules) { $schedules['every_minute'] = array( 'interval' => 60, 'display' => 'Every Minute' ); $schedules['every_5_minutes'] = array( 'interval' => 5 * 60, 'display' => 'Every 5 Minutes' ); $schedules['every_15_minutes'] = array( 'interval' => 15 * 60, 'display' => 'Every 15 Minutes' ); $schedules['every_30_minutes'] = array( 'interval' => 30 * 60, 'display' => 'Every 30 Minutes' ); $schedules['hourly'] = array( 'interval' => HOUR_IN_SECONDS, 'display' => 'Every Hour' ); $schedules['every_2_hours'] = array( 'interval' => 2 * HOUR_IN_SECONDS, 'display' => 'Every 2 Hours' ); $schedules['every_3_hours'] = array( 'interval' => 3 * HOUR_IN_SECONDS, 'display' => 'Every 3 Hours' ); $schedules['every_6_hours'] = array( 'interval' => 6 * HOUR_IN_SECONDS, 'display' => 'Every 6 Hours' ); $schedules['every_12_hours'] = array( 'interval' => 12 * HOUR_IN_SECONDS, 'display' => 'Every 12 Hours' ); $schedules['daily'] = array( 'interval' => DAY_IN_SECONDS, 'display' => 'Daily' ); $schedules['every_2_days'] = array( 'interval' => 2 * DAY_IN_SECONDS, 'display' => 'Every 2 Days' ); $schedules['every_3_days'] = array( 'interval' => 3 * DAY_IN_SECONDS, 'display' => 'Every 3 Days' ); // Add custom interval if set $custom_interval = get_option('ainews_custom_interval', 60); if ($custom_interval >= 1 && $custom_interval <= 10080) { $schedules['ainews_custom'] = array( 'interval' => $custom_interval * 60, 'display' => sprintf('Every %d minutes (custom)', $custom_interval) ); } return $schedules; } // Schedule automatic generation - but only when explicitly enabled add_action('init', 'ainews_schedule_articles'); function ainews_schedule_articles() { $interval = get_option('ainews_schedule_interval', 'manual'); $auto_enabled = get_option('ainews_auto_enabled', false); // If auto is disabled or manual, ensure it's cleared and exit if ($interval === 'manual' || !$auto_enabled) { wp_clear_scheduled_hook('ainews_generate_articles'); return; } // Only schedule if not already scheduled if (!wp_next_scheduled('ainews_generate_articles')) { $schedule_name = ($interval === 'custom') ? 'ainews_custom' : $interval; // Schedule slightly in the future to avoid immediate repeated runs wp_schedule_event(time() + 60, $schedule_name, 'ainews_generate_articles'); } } // Handle scheduled article generation add_action('ainews_generate_articles', 'ainews_scheduled_generation'); function ainews_scheduled_generation() { $api_key = get_option('ainews_api_key'); if (empty($api_key)) { return; } // Check if paused if (get_option('ainews_schedule_paused', false)) { return; } $count = (int) get_option('ainews_article_count', 1); $language = get_option('ainews_language', 'en'); $selected_topics = get_option('ainews_selected_topics', 'artificial_intelligence'); // Convert selected topics to array $topics_array = array_filter(explode(',', $selected_topics)); if (empty($topics_array)) { $topics_array = array('artificial_intelligence'); } $generated_count = 0; for ($i = 0; $i < $count; $i++) { // Randomly select a topic from the selected topics $topic_key = $topics_array[array_rand($topics_array)]; $post_id = ainews_generate_single_article($language, $topic_key); if ($post_id) { $generated_count++; } sleep(2); // Rate limiting } // Update statistics if ($generated_count > 0) { $current_total = (int) get_option('ainews_auto_generated_count', 0); update_option('ainews_auto_generated_count', $current_total + $generated_count); update_option('ainews_last_auto_run', current_time('mysql')); } } // Load prompts from JSON file (supports uploads override) function ainews_get_prompts() { // Preferred override in uploads directory $uploads = wp_upload_dir(); $uploads_override = trailingslashit($uploads['basedir']) . 'ainews/prompts.json'; $candidate_paths = array(); if (!empty($uploads['basedir'])) { $candidate_paths[] = $uploads_override; } // Fallback to plugin directory file $candidate_paths[] = AINEWS_PLUGIN_DIR . 'prompts.json'; $last_error = ''; foreach ($candidate_paths as $path) { if (!file_exists($path)) { $last_error = 'File does not exist: ' . $path; continue; } $content = @file_get_contents($path); if ($content === false) { $last_error = 'Failed to read file: ' . $path; continue; } $decoded = json_decode($content, true); if (json_last_error() !== JSON_ERROR_NONE) { $last_error = 'JSON decode error at ' . $path . ': ' . json_last_error_msg(); continue; } // Successfully loaded return $decoded; } if (!empty($last_error)) { error_log('AI News: ' . $last_error); } return false; } // Get current prompt based on settings function ainews_get_current_prompt($language = 'en', $topic_key = '') { $prompt_type = get_option('ainews_prompt_type', 'default'); if ($prompt_type === 'custom') { $custom_prompt = get_option('ainews_custom_prompt'); if (!empty($custom_prompt)) { return ainews_replace_topic_placeholder($custom_prompt, $language, $topic_key); } } $prompts = ainews_get_prompts(); if (!$prompts) { // Fallback to hardcoded prompts if file doesn't exist if ($language === 'zh') { $fallback = '写一篇关于{topic}最新发展的新闻文章。请包含: 1. 吸引人的标题 2. 简短的导语 3. 2-3段详细内容 4. 信息丰富且引人入胜 请确保内容准确、专业,适合新闻发布。'; } else { $fallback = 'Write a news article about recent developments in {topic}. Include: 1. A compelling headline 2. A brief introduction 3. 2-3 paragraphs of detailed content 4. Make it informative and engaging Ensure the content is accurate, professional, and suitable for publication.'; } return ainews_replace_topic_placeholder($fallback, $language, $topic_key); } $prompt_template = ''; if ($prompt_type === 'default') { $prompt_template = $prompts['default_prompts'][$language]['prompt']; } elseif (strpos($prompt_type, 'custom_') === 0) { $index = (int) str_replace('custom_', '', $prompt_type); if (isset($prompts['custom_prompts'][$language][$index])) { $prompt_template = $prompts['custom_prompts'][$language][$index]['prompt']; } } if (empty($prompt_template)) { $prompt_template = $prompts['default_prompts'][$language]['prompt']; } return ainews_replace_topic_placeholder($prompt_template, $language, $topic_key); } // Replace {topic} placeholder in prompt with actual topic name function ainews_replace_topic_placeholder($prompt, $language, $topic_key) { if (empty($topic_key)) { return str_replace('{topic}', 'artificial intelligence', $prompt); } $prompts = ainews_get_prompts(); if (!$prompts || !isset($prompts['news_topics'][$language])) { return str_replace('{topic}', 'artificial intelligence', $prompt); } // Find topic name from all categories $topic_name = ''; foreach ($prompts['news_topics'][$language] as $category) { if (isset($category[$topic_key])) { $topic_name = $category[$topic_key]; break; } } if (empty($topic_name)) { $topic_name = 'artificial intelligence'; } return str_replace('{topic}', $topic_name, $prompt); } // Generate single article function function ainews_generate_single_article($language = 'en', $topic_key = '') { $api_key = get_option('ainews_api_key'); if (empty($api_key)) { return false; } $prompt = ainews_get_current_prompt($language, $topic_key); $response = wp_remote_post('https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp:generateContent?key=' . $api_key, array( 'headers' => array('Content-Type' => 'application/json'), 'body' => json_encode(array( 'contents' => array(array( 'parts' => array(array('text' => $prompt)) )) )), 'timeout' => 30 )); if (is_wp_error($response)) { $error_msg = 'API request failed - ' . $response->get_error_message(); error_log('AI News: ' . $error_msg); return false; } $code = wp_remote_retrieve_response_code($response); $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); if ($code !== 200) { $error_msg = 'API error (HTTP ' . $code . '): ' . $body; error_log('AI News: ' . $error_msg); return false; } if (!isset($data['candidates'][0]['content']['parts'][0]['text'])) { $error_msg = 'Invalid API response structure: ' . $body; error_log('AI News: ' . $error_msg); return false; } if (isset($data['candidates'][0]['content']['parts'][0]['text'])) { $content = $data['candidates'][0]['content']['parts'][0]['text']; // Extract title and content $lines = explode("\n", trim($content)); $title = trim($lines[0], "# \t\n\r\0\x0B*"); $article_content = implode("\n", array_slice($lines, 1)); // Create post $post_data = array( 'post_title' => $title, 'post_content' => wpautop($article_content), 'post_status' => get_option('ainews_post_status', 'draft'), 'post_type' => 'post' ); // Add category if selected $category = get_option('ainews_post_category'); if (!empty($category)) { $post_data['post_category'] = array($category); } $post_id = wp_insert_post($post_data); if ($post_id) { // Add meta to track AI generated posts add_post_meta($post_id, '_ainews_generated', true); add_post_meta($post_id, '_ainews_language', $language); // Trigger featured image generation hook do_action('ainews_after_article_generated', $post_id, $title, $article_content, $language); // Log to history table global $wpdb; $table_name = $wpdb->prefix . 'ainews_history'; $prompts = ainews_get_prompts(); $topic_name = ''; // Get topic name from prompts if ($prompts && isset($prompts['news_topics'][$language])) { foreach ($prompts['news_topics'][$language] as $category) { if (isset($category[$topic_key])) { $topic_name = $category[$topic_key]; break; } } } if (empty($topic_name)) { $topic_name = $topic_key ?: 'artificial intelligence'; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $wpdb->insert( $table_name, [ 'topic' => $topic_name, 'title' => $title, 'post_id' => $post_id, 'language' => $language, ] ); return $post_id; } } return false; } // Sanitization callback functions for register_setting function ainews_sanitize_api_key($input) { return sanitize_text_field($input); } function ainews_sanitize_post_category($input) { return absint($input); } function ainews_sanitize_schedule_interval($input) { $allowed_values = array('manual', 'hourly', 'daily', 'weekly', 'custom'); return in_array($input, $allowed_values) ? $input : 'manual'; } function ainews_sanitize_article_count($input) { $count = absint($input); return ($count >= 1 && $count <= 10) ? $count : 1; } function ainews_sanitize_language($input) { $allowed_values = array('en', 'zh'); return in_array($input, $allowed_values) ? $input : 'en'; } function ainews_sanitize_selected_topics($input) { return sanitize_text_field($input); } function ainews_sanitize_post_status($input) { $allowed_values = array('draft', 'publish', 'pending'); return in_array($input, $allowed_values) ? $input : 'draft'; } function ainews_sanitize_prompt_type($input) { $allowed_values = array('default', 'custom'); return in_array($input, $allowed_values) ? $input : 'default'; } function ainews_sanitize_prompt_language($input) { $allowed_values = array('en', 'zh'); return in_array($input, $allowed_values) ? $input : 'en'; } function ainews_sanitize_custom_interval($input) { $interval = absint($input); return ($interval >= 1 && $interval <= 10080) ? $interval : 60; } ?>