'; public $name_plan; public function __construct() { // Prevent multiple initialization of hooks and actions // Check if this instance's class has already been initialized $class_name = get_class($this); // If already initialized, skip hook registration if (self::$initialized) { // Still set basic properties for this instance $this->name_plan = __('Auto Create Categories', 'ai-auto-tool'); $this->active_option_name = 'AIAutoTool_auto_create_categories_active'; $this->active = get_option($this->active_option_name, 'false'); return; } // Mark as initialized self::$initialized = true; $this->name_plan = __('Auto Create Categories', 'ai-auto-tool'); $this->active_option_name = 'AIAutoTool_auto_create_categories_active'; $this->active = get_option($this->active_option_name, 'false'); if ($this->active == 'true') { $this->init(); } // Register AJAX handler only once add_action('wp_ajax_update_active_option_canonical_' . $this->active_option_name, array($this, 'update_active_option_callback')); } public function update_active_option_callback() { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('manage_options')) { wp_die(__('Permission denied', 'ai-auto-tool'), '', array('response' => 403)); } if (isset($_POST['active'])) { $active = sanitize_text_field($_POST['active']); update_option($this->active_option_name, $active, null, 'no'); print_r($active); } wp_die(); } public function init() { // Prevent duplicate hooks registration in init() if (self::$init_hooks_registered) { return; } self::$init_hooks_registered = true; // Enqueue scripts and styles on category edit page add_action('admin_enqueue_scripts', array($this, 'enqueue_assets')); // Add meta box to category edit page add_action('admin_init', array($this, 'add_category_meta_box')); // Register settings add_action('admin_init', array($this, 'register_settings')); // AJAX handlers add_action('wp_ajax_aiautotool_generate_category_tree', array($this, 'ajax_generate_category_tree')); add_action('wp_ajax_aiautotool_create_categories', array($this, 'ajax_create_categories')); // AJAX handlers for auto write descriptions add_action('wp_ajax_aiautotool_get_categories', array($this, 'ajax_get_categories')); add_action('wp_ajax_aiautotool_generate_category_description', array($this, 'ajax_generate_category_description')); add_action('wp_ajax_aiautotool_save_category_description', array($this, 'ajax_save_category_description')); add_action('wp_ajax_aiautotool_schedule_cron_descriptions', array($this, 'ajax_schedule_cron_descriptions')); add_action('wp_ajax_aiautotool_get_cron_descriptions_status', array($this, 'ajax_get_cron_status')); add_action('wp_ajax_aiautotool_get_cron_status', array($this, 'ajax_get_cron_status')); // Cron job for background processing add_filter('cron_schedules', array($this, 'add_category_desc_cron_schedule')); add_action('aiautotool_auto_write_category_descriptions', array($this, 'cron_write_category_descriptions')); // Initialize cron if there are pending categories $this->maybe_schedule_cron(); } /** * Maybe schedule cron if there are pending categories */ private function maybe_schedule_cron() { $pending = get_option('aiautotool_pending_category_descriptions', array()); if (!empty($pending) && !wp_next_scheduled('aiautotool_auto_write_category_descriptions')) { wp_schedule_event(time(), 'aiautotool_category_desc_interval', 'aiautotool_auto_write_category_descriptions'); } } /** * Register settings */ public function register_settings() { register_setting( 'aiautotool_auto_categories_settings', 'aiautotool_auto_categories_enabled_taxonomies', array( 'type' => 'array', 'sanitize_callback' => array($this, 'sanitize_taxonomies'), 'default' => array('category') ) ); } /** * Sanitize taxonomies array */ public function sanitize_taxonomies($taxonomies) { if (!is_array($taxonomies)) { return array('category'); } // Validate each taxonomy exists $valid_taxonomies = get_taxonomies(array('public' => true)); $sanitized = array(); foreach ($taxonomies as $taxonomy) { $taxonomy = sanitize_text_field($taxonomy); if (in_array($taxonomy, $valid_taxonomies)) { $sanitized[] = $taxonomy; } } // Always include category if empty if (empty($sanitized)) { $sanitized = array('category'); } return $sanitized; } /** * Enqueue scripts and styles */ public function enqueue_assets($hook) { // Only load on taxonomy edit page if ($hook !== 'edit-tags.php' && $hook !== 'term.php') { return; } global $current_screen; $enabled_taxonomies = $this->get_enabled_taxonomies(); if (!isset($current_screen->taxonomy) || !in_array($current_screen->taxonomy, $enabled_taxonomies)) { return; } // Get plugin URL for Font Awesome $plugin_url = defined('AIAUTOTOOL_URI') ? AIAUTOTOOL_URI : plugin_dir_url(dirname(dirname(dirname(__FILE__)))); // Enqueue Font Awesome for icons wp_enqueue_style( 'font-awesome-auto-categories', $plugin_url . 'js/fontawesome/css/all.min.css', array(), defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '7.1.0' ); // Enqueue CSS wp_enqueue_style( 'auto-create-categories-css', plugin_dir_url(__FILE__) . 'assets/css/auto-create-categories.css', array('font-awesome-auto-categories'), defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.0' ); // Enqueue JS wp_enqueue_script( 'auto-create-categories-js', plugin_dir_url(__FILE__) . 'assets/js/auto-create-categories.js', array('jquery'), defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.0', true ); // Localize script wp_localize_script('auto-create-categories-js', 'autoCreateCategories', array( 'ajaxurl' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('aiautotool_auto_categories_nonce'), 'ajaxurl_settings' => admin_url('admin-ajax.php'), 'strings' => array( 'generating' => __('Generating category list...', 'ai-auto-tool'), 'error' => __('An error occurred. Please try again.', 'ai-auto-tool'), 'creating' => __('Creating categories...', 'ai-auto-tool'), 'success' => __('Categories created successfully!', 'ai-auto-tool'), 'confirm_delete' => __('Are you sure you want to delete this category?', 'ai-auto-tool'), 'please_enter_topic' => __('Please enter a topic', 'ai-auto-tool'), 'invalid_data' => __('Invalid data', 'ai-auto-tool'), 'no_data_to_add' => __('No category data to add', 'ai-auto-tool'), 'created_successfully' => __('Created successfully', 'ai-auto-tool'), 'categories' => __('categories', 'ai-auto-tool'), 'errors' => __('Errors', 'ai-auto-tool'), 'error_occurred' => __('An error occurred while creating categories', 'ai-auto-tool'), 'analyzing' => __('Analyzing and generating category tree...', 'ai-auto-tool'), 'delete' => __('Delete', 'ai-auto-tool'), 'category_tree_list' => __('Category Tree List:', 'ai-auto-tool'), 'step_enter_topic' => __('Enter Topic', 'ai-auto-tool'), 'step_review_edit' => __('Review & Edit', 'ai-auto-tool'), 'previous' => __('Previous', 'ai-auto-tool'), 'next' => __('Next', 'ai-auto-tool'), // New strings for description feature 'auto_write_descriptions' => __('Auto Write Category Descriptions', 'ai-auto-tool'), 'select_categories' => __('Select Categories', 'ai-auto-tool'), 'generating_descriptions' => __('Generating Descriptions', 'ai-auto-tool'), 'select_categories_first' => __('Please select at least one category', 'ai-auto-tool'), 'generating_desc_for' => __('Generating description for', 'ai-auto-tool'), 'description_generated' => __('Description generated successfully', 'ai-auto-tool'), 'description_saved' => __('Description saved successfully', 'ai-auto-tool'), 'all_descriptions_completed' => __('All descriptions completed!', 'ai-auto-tool'), 'enable_cron' => __('Enable Auto Run (Cron)', 'ai-auto-tool'), 'run_now' => __('Run Now', 'ai-auto-tool'), 'processing' => __('Processing...', 'ai-auto-tool'), 'completed' => __('Completed', 'ai-auto-tool'), 'failed' => __('Failed', 'ai-auto-tool'), 'view_cron_status' => __('View Cron Status', 'ai-auto-tool'), 'pending' => __('Pending', 'ai-auto-tool'), 'completed_label' => __('Completed', 'ai-auto-tool'), 'next_run' => __('Next Run', 'ai-auto-tool'), 'cron_status' => __('Cron Status', 'ai-auto-tool'), 'not_scheduled' => __('Not Scheduled', 'ai-auto-tool'), 'next_category' => __('Next Category to Process', 'ai-auto-tool'), 'position' => __('Position', 'ai-auto-tool'), 'pending_categories' => __('Pending Categories', 'ai-auto-tool'), 'no' => __('No.', 'ai-auto-tool'), 'category_name' => __('Category Name', 'ai-auto-tool'), 'taxonomy' => __('Taxonomy', 'ai-auto-tool'), 'status' => __('Status', 'ai-auto-tool'), 'waiting' => __('Waiting', 'ai-auto-tool'), 'no_pending' => __('No pending categories. All descriptions have been generated!', 'ai-auto-tool'), 'recently_completed' => __('Recently Completed', 'ai-auto-tool'), 'showing_last_20' => __('Showing last 20 completed. Total:', 'ai-auto-tool'), ) )); } /** * Add meta box to category edit page */ public function add_category_meta_box() { // Prevent duplicate hooks registration if (self::$hooks_registered) { return; } global $pagenow; // Only on edit-tags.php if ($pagenow === 'edit-tags.php') { // Get enabled taxonomies $enabled_taxonomies = $this->get_enabled_taxonomies(); // Add hooks for each enabled taxonomy foreach ($enabled_taxonomies as $taxonomy) { add_action($taxonomy . '_add_form_fields', array($this, 'render_category_meta_box')); add_action($taxonomy . '_edit_form_fields', array($this, 'render_category_meta_box')); } // Also add to admin_footer for the list page add_action('admin_footer', array($this, 'render_category_meta_box')); // Mark as registered self::$hooks_registered = true; } } /** * Get enabled taxonomies */ private function get_enabled_taxonomies() { $enabled = get_option('aiautotool_auto_categories_enabled_taxonomies', array('category')); // Ensure it's an array if (!is_array($enabled)) { $enabled = array('category'); } return $enabled; } /** * Render meta box HTML */ public function render_category_meta_box() { // Prevent duplicate rendering - only render once per page load if (self::$rendered) { return; } global $current_screen, $pagenow; // Check if current taxonomy is enabled $enabled_taxonomies = $this->get_enabled_taxonomies(); // Determine current taxonomy $current_taxonomy = ''; if (isset($current_screen->taxonomy)) { $current_taxonomy = $current_screen->taxonomy; } elseif ($pagenow === 'edit-tags.php' && isset($_GET['taxonomy'])) { $current_taxonomy = sanitize_text_field($_GET['taxonomy']); } // Only render if taxonomy is enabled if (empty($current_taxonomy) || !in_array($current_taxonomy, $enabled_taxonomies)) { return; } // Mark as rendered to prevent duplicate self::$rendered = true; ?> __('Permission denied', 'ai-auto-tool'))); } $topic = isset($_POST['topic']) ? sanitize_text_field($_POST['topic']) : ''; $language = isset($_POST['language']) ? sanitize_text_field($_POST['language']) : 'en'; if (empty($topic)) { wp_send_json_error(array('message' => __('Please enter a topic', 'ai-auto-tool'))); } // Validate language - use languageCodes from parent class (rendersetting) $supported_languages = $this->languageCodes; if (!isset($supported_languages[$language])) { $language = 'en'; // Default to English if invalid } $language_name = isset($supported_languages[$language]) ? $supported_languages[$language] : 'English'; // Check if AI Helper is available if (!class_exists('AIAutotool_AI_Helper')) { wp_send_json_error(array('message' => __('AI Helper is not available. Please check AI Provider configuration.', 'ai-auto-tool'))); } if (!AIAutotool_AI_Helper::is_available()) { wp_send_json_error(array('message' => __('AI Provider is not configured. Please configure it in AI Provider Settings.', 'ai-auto-tool'))); } // Build prompt for AI with language $prompt = $this->build_category_tree_prompt($topic, $language, $language_name); // Call AI $messages = array( array( 'role' => 'system', 'content' => __('You are an SEO and website content architecture expert. Your task is to create a category tree (site structure) optimized for SEO using the topic cluster model. Return ONLY JSON result, no other text.', 'ai-auto-tool') ), array( 'role' => 'user', 'content' => $prompt ) ); $result = AIAutotool_AI_Helper::chat($messages, array( 'temperature' => 0.7, 'max_tokens' => 2000 )); if (!$result['success']) { $error_message = isset($result['error']) && !empty($result['error']) ? $result['error'] : 'Unknown error occurred. Please check your AI provider configuration and try again.'; // Log detailed error for debugging wp_send_json_error(array( 'message' => __('Error calling AI: ', 'ai-auto-tool') . $error_message )); } $content = $result['content']; // Extract JSON from response $json_data = $this->extract_json_from_response($content); if (!$json_data) { wp_send_json_error(array('message' => __('Unable to parse AI response. Please try again.', 'ai-auto-tool'))); } // Validate structure if (!isset($json_data['mainTopic']) || !isset($json_data['categoryTree'])) { wp_send_json_error(array('message' => __('Invalid data structure.', 'ai-auto-tool'))); } wp_send_json_success($json_data); } /** * Build prompt for category tree generation */ private function build_category_tree_prompt($topic, $language_code = 'en', $language_name = 'English') { $prompt = sprintf(__("You are an SEO and website content architecture expert. Your task: - Input: ** %s ** - Create a **category tree structure** (site structure). - IMPORTANT: All category names must be in %s language. - Categories must be clearly hierarchical: - Main Category - Level 1 Sub-category - Level 2 Sub-category (if needed) - Content must: - Cover the entire topic - No duplicates - SEO optimized using topic clusters - Useful for users and easy to navigate - All category names written in %s - Return the following JSON format (NO OTHER TEXT, JSON ONLY): { \"mainTopic\": \"%s\", \"categoryTree\": [ { \"category\": \"Main category name in %s\", \"sub\": [ { \"subCategory\": \"Sub category 1 name in %s\", \"sub\": [ \"Level 2 sub category in %s (if any)\" ] } ] } ] } Start! Create a category tree for a website with topic: **%s** in %s language.", 'ai-auto-tool'), $topic, $language_name, $language_name, $topic, $language_name, $language_name, $language_name, $topic, $language_name ); return $prompt; } /** * Extract JSON from AI response */ private function extract_json_from_response($content) { // Try to find JSON in the response // Remove markdown code blocks if present $content = preg_replace('/```json\s*/', '', $content); $content = preg_replace('/```\s*/', '', $content); $content = trim($content); // Try to find JSON object $pattern = '/\{[\s\S]*\}/'; preg_match($pattern, $content, $matches); if (!empty($matches[0])) { $json_string = $matches[0]; $json_data = json_decode($json_string, true); if (json_last_error() === JSON_ERROR_NONE) { return $json_data; } } // Try direct decode $json_data = json_decode($content, true); if (json_last_error() === JSON_ERROR_NONE) { return $json_data; } return false; } /** * AJAX: Create categories from tree */ public function ajax_create_categories() { check_ajax_referer('aiautotool_auto_categories_nonce', 'nonce'); if (!current_user_can('manage_options')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } $category_tree = isset($_POST['categoryTree']) ? $_POST['categoryTree'] : array(); $taxonomy = isset($_POST['taxonomy']) ? sanitize_text_field($_POST['taxonomy']) : 'category'; // Validate taxonomy is enabled $enabled_taxonomies = $this->get_enabled_taxonomies(); if (!in_array($taxonomy, $enabled_taxonomies)) { wp_send_json_error(array('message' => __('Taxonomy not enabled', 'ai-auto-tool'))); } if (empty($category_tree) || !is_array($category_tree)) { wp_send_json_error(array('message' => __('Invalid category tree data', 'ai-auto-tool'))); } $created = array(); $errors = array(); // Process each main category foreach ($category_tree as $main_category) { if (!isset($main_category['category']) || empty($main_category['category'])) { continue; } $main_cat_name = sanitize_text_field($main_category['category']); // Create main category $main_cat_id = $this->create_category($main_cat_name, 0, $taxonomy); if (is_wp_error($main_cat_id)) { $errors[] = sprintf(__('Error creating category "%s": %s', 'ai-auto-tool'), $main_cat_name, $main_cat_id->get_error_message()); continue; } $created[] = array( 'name' => $main_cat_name, 'id' => $main_cat_id, 'parent' => 0, 'level' => 0 ); // Process sub-categories level 1 if (isset($main_category['sub']) && is_array($main_category['sub'])) { foreach ($main_category['sub'] as $sub1) { if (!isset($sub1['subCategory']) || empty($sub1['subCategory'])) { continue; } $sub1_name = sanitize_text_field($sub1['subCategory']); $sub1_id = $this->create_category($sub1_name, $main_cat_id, $taxonomy); if (is_wp_error($sub1_id)) { $errors[] = sprintf(__('Error creating sub-category "%s": %s', 'ai-auto-tool'), $sub1_name, $sub1_id->get_error_message()); continue; } $created[] = array( 'name' => $sub1_name, 'id' => $sub1_id, 'parent' => $main_cat_id, 'level' => 1 ); // Process sub-categories level 2 if (isset($sub1['sub']) && is_array($sub1['sub'])) { foreach ($sub1['sub'] as $sub2_name) { if (empty($sub2_name)) { continue; } $sub2_name = sanitize_text_field($sub2_name); $sub2_id = $this->create_category($sub2_name, $sub1_id, $taxonomy); if (is_wp_error($sub2_id)) { $errors[] = sprintf(__('Error creating level 2 sub-category "%s": %s', 'ai-auto-tool'), $sub2_name, $sub2_id->get_error_message()); continue; } $created[] = array( 'name' => $sub2_name, 'id' => $sub2_id, 'parent' => $sub1_id, 'level' => 2 ); } } } } } wp_send_json_success(array( 'created' => $created, 'errors' => $errors, 'total' => count($created) )); } /** * Create a category */ private function create_category($name, $parent_id = 0, $taxonomy = 'category') { // Check if category already exists $existing = term_exists($name, $taxonomy, $parent_id); if ($existing !== null && $existing !== 0) { // Category exists, return its ID return is_array($existing) ? $existing['term_id'] : $existing; } // Create new category $result = wp_insert_term( $name, $taxonomy, array( 'parent' => $parent_id ) ); if (is_wp_error($result)) { return $result; } return $result['term_id']; } /** * Render feature settings */ public function render_setting() { if ($this->active != "true") { return ''; } // Save settings if (isset($_POST['aiautotool_auto_categories_save_settings']) && check_admin_referer('aiautotool_auto_categories_settings')) { $enabled_taxonomies = isset($_POST['enabled_taxonomies']) ? array_map('sanitize_text_field', $_POST['enabled_taxonomies']) : array(); update_option('aiautotool_auto_categories_enabled_taxonomies', $enabled_taxonomies, false); echo '

' . esc_html__('Settings saved successfully!', 'ai-auto-tool') . '

'; } $enabled_taxonomies = get_option('aiautotool_auto_categories_enabled_taxonomies', array('category')); // Get all taxonomies $taxonomies = get_taxonomies(array('public' => true), 'objects'); ?> active == "true") { echo ''; } } /** * Render feature description */ public function render_feature() { // Load feature descriptions require_once plugin_dir_path(dirname(__FILE__)) . '../lib/feature-descriptions.php'; $autoToolBox = new AutoToolBox( $this->icon . ' ' . $this->name_plan, __('Automatically create a category tree structure based on your website topic. AI will analyze and generate an SEO-optimized category structure.', 'ai-auto-tool'), "https://doc.aiautotool.com/features/auto-create-categories", $this->active_option_name, $this->active, plugins_url('../../images/logo.svg', __FILE__) ); echo ($autoToolBox->generateHTML()); } /** * AJAX: Get all categories */ public function ajax_get_categories() { check_ajax_referer('aiautotool_auto_categories_nonce', 'nonce'); if (!current_user_can('manage_options')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } // Get taxonomy from request, default to category $taxonomy = isset($_POST['taxonomy']) ? sanitize_text_field($_POST['taxonomy']) : 'category'; // Validate taxonomy is enabled $enabled_taxonomies = $this->get_enabled_taxonomies(); if (!in_array($taxonomy, $enabled_taxonomies)) { wp_send_json_error(array('message' => __('Taxonomy not enabled', 'ai-auto-tool'))); } $categories = get_terms(array( 'taxonomy' => $taxonomy, 'hide_empty' => false, 'orderby' => 'name', 'order' => 'ASC' )); if (is_wp_error($categories)) { wp_send_json_error(array('message' => $categories->get_error_message())); } $formatted_categories = array(); foreach ($categories as $category) { $formatted_categories[] = array( 'id' => $category->term_id, 'name' => $category->name, 'slug' => $category->slug, 'parent' => $category->parent, 'description' => $category->description, 'has_description' => !empty($category->description) ); } wp_send_json_success($formatted_categories); } /** * AJAX: Generate category description */ public function ajax_generate_category_description() { check_ajax_referer('aiautotool_auto_categories_nonce', 'nonce'); if (!current_user_can('manage_options')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } $category_id = isset($_POST['category_id']) ? intval($_POST['category_id']) : 0; $taxonomy = isset($_POST['taxonomy']) ? sanitize_text_field($_POST['taxonomy']) : 'category'; if (!$category_id) { wp_send_json_error(array('message' => __('Invalid category ID', 'ai-auto-tool'))); } // Validate taxonomy is enabled $enabled_taxonomies = $this->get_enabled_taxonomies(); if (!in_array($taxonomy, $enabled_taxonomies)) { wp_send_json_error(array('message' => __('Taxonomy not enabled', 'ai-auto-tool'))); } $category = get_term($category_id, $taxonomy); if (!$category || is_wp_error($category)) { wp_send_json_error(array('message' => __('Category not found', 'ai-auto-tool'))); } // Check if AI Helper is available if (!class_exists('AIAutotool_AI_Helper')) { wp_send_json_error(array('message' => __('AI Helper is not available. Please check AI Provider configuration.', 'ai-auto-tool'))); } if (!AIAutotool_AI_Helper::is_available()) { wp_send_json_error(array('message' => __('AI Provider is not configured. Please configure it in AI Provider Settings.', 'ai-auto-tool'))); } // Build prompt for description generation $prompt = $this->build_description_prompt($category); // Call AI $messages = array( array( 'role' => 'system', 'content' => __('You are an SEO expert. Generate a concise, SEO-optimized description for a WordPress category. The description should be informative, keyword-rich, and between 100-200 words. Return ONLY the description text, no other text or formatting.', 'ai-auto-tool') ), array( 'role' => 'user', 'content' => $prompt ) ); $result = AIAutotool_AI_Helper::chat($messages, array( 'temperature' => 0.7, 'max_tokens' => 300 )); if (!$result['success']) { $error_message = isset($result['error']) && !empty($result['error']) ? $result['error'] : 'Unknown error occurred. Please check your AI provider configuration and try again.'; // Log detailed error for debugging wp_send_json_error(array( 'message' => __('Error calling AI: ', 'ai-auto-tool') . $error_message )); } $description = trim($result['content']); // Clean up description (remove markdown code blocks if any) $description = preg_replace('/```[\s\S]*?```/', '', $description); $description = trim($description); wp_send_json_success(array( 'category_id' => $category_id, 'description' => $description )); } /** * Build prompt for description generation */ private function build_description_prompt($category) { $site_name = get_bloginfo('name'); $site_description = get_bloginfo('description'); $parent_info = ''; if ($category->parent > 0) { $parent = get_category($category->parent); if ($parent) { $parent_info = sprintf(__('Parent category: %s. ', 'ai-auto-tool'), $parent->name); } } $prompt = sprintf( __('Generate an SEO-optimized description for a WordPress category with the following details: Website: %s Site Description: %s Category Name: %s Category Slug: %s %s Create a professional, SEO-friendly description (100-200 words) that: - Clearly explains what this category is about - Includes relevant keywords naturally - Is informative and useful for visitors - Encourages engagement - Is written in a professional tone Return ONLY the description text, no introduction or explanation.', 'ai-auto-tool'), $site_name, $site_description, $category->name, $category->slug, $parent_info ); return $prompt; } /** * AJAX: Save category description */ public function ajax_save_category_description() { check_ajax_referer('aiautotool_auto_categories_nonce', 'nonce'); if (!current_user_can('manage_options')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } $category_id = isset($_POST['category_id']) ? intval($_POST['category_id']) : 0; $description = isset($_POST['description']) ? wp_kses_post($_POST['description']) : ''; $taxonomy = isset($_POST['taxonomy']) ? sanitize_text_field($_POST['taxonomy']) : 'category'; if (!$category_id) { wp_send_json_error(array('message' => __('Invalid category ID', 'ai-auto-tool'))); } // Validate taxonomy is enabled $enabled_taxonomies = $this->get_enabled_taxonomies(); if (!in_array($taxonomy, $enabled_taxonomies)) { wp_send_json_error(array('message' => __('Taxonomy not enabled', 'ai-auto-tool'))); } $result = wp_update_term($category_id, $taxonomy, array( 'description' => $description )); if (is_wp_error($result)) { wp_send_json_error(array('message' => $result->get_error_message())); } wp_send_json_success(array( 'category_id' => $category_id, 'message' => __('Description saved successfully', 'ai-auto-tool') )); } /** * AJAX: Schedule cron job for descriptions */ public function ajax_schedule_cron_descriptions() { check_ajax_referer('aiautotool_auto_categories_nonce', 'nonce'); if (!current_user_can('manage_options')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } $category_ids = isset($_POST['category_ids']) ? $_POST['category_ids'] : array(); if (empty($category_ids) || !is_array($category_ids)) { wp_send_json_error(array('message' => __('Invalid category IDs', 'ai-auto-tool'))); } // Get taxonomy from request, default to category $taxonomy = isset($_POST['taxonomy']) ? sanitize_text_field($_POST['taxonomy']) : 'category'; // Validate taxonomy is enabled $enabled_taxonomies = $this->get_enabled_taxonomies(); if (!in_array($taxonomy, $enabled_taxonomies)) { wp_send_json_error(array('message' => __('Taxonomy not enabled', 'ai-auto-tool'))); } // Filter out categories that already have descriptions $pending_ids = array(); $pending_data = array(); // Store taxonomy for each category foreach ($category_ids as $cat_id) { $cat_id = intval($cat_id); if ($cat_id > 0) { $category = get_term($cat_id, $taxonomy); if ($category && !is_wp_error($category) && empty($category->description)) { $pending_ids[] = $cat_id; $pending_data[$cat_id] = $taxonomy; } } } if (empty($pending_ids)) { wp_send_json_success(array('message' => __('All selected categories already have descriptions', 'ai-auto-tool'))); } // Save pending categories and their taxonomies update_option('aiautotool_pending_category_descriptions', $pending_ids); update_option('aiautotool_pending_category_descriptions_data', $pending_data); // Schedule cron event if not already scheduled if (!wp_next_scheduled('aiautotool_auto_write_category_descriptions')) { wp_schedule_event(time(), 'aiautotool_category_desc_interval', 'aiautotool_auto_write_category_descriptions'); } wp_send_json_success(array( 'message' => sprintf(__('%d categories queued for background processing', 'ai-auto-tool'), count($pending_ids)), 'count' => count($pending_ids) )); } /** * Add custom cron schedule for category descriptions */ public function add_category_desc_cron_schedule($schedules) { $schedules['aiautotool_category_desc_interval'] = array( 'interval' => 300, // 5 minutes 'display' => __('Every 5 Minutes (Category Descriptions)', 'ai-auto-tool') ); return $schedules; } /** * Cron job: Write category descriptions in background */ public function cron_write_category_descriptions() { // Ensure textdomain is loaded (important for cron jobs) // Only load if 'init' action has fired (WordPress 6.7.0+ requirement) if (!is_textdomain_loaded('ai-auto-tool')) { if (did_action('init')) { if (function_exists('aiautotool_load_textdomain')) { aiautotool_load_textdomain(); } } } // Get pending categories from option $pending_categories = get_option('aiautotool_pending_category_descriptions', array()); if (empty($pending_categories)) { return; } // Process one category at a time $category_id = array_shift($pending_categories); if (!$category_id) { update_option('aiautotool_pending_category_descriptions', array()); return; } // Get taxonomy from pending data or default to category $pending_data = get_option('aiautotool_pending_category_descriptions_data', array()); $taxonomy = isset($pending_data[$category_id]) ? $pending_data[$category_id] : 'category'; // Validate taxonomy is enabled $enabled_taxonomies = $this->get_enabled_taxonomies(); if (!in_array($taxonomy, $enabled_taxonomies)) { // Skip if taxonomy not enabled update_option('aiautotool_pending_category_descriptions', $pending_categories); return; } $category = get_term($category_id, $taxonomy); if (!$category || is_wp_error($category)) { // Skip invalid category update_option('aiautotool_pending_category_descriptions', $pending_categories); return; } // Skip if already has description if (!empty($category->description)) { update_option('aiautotool_pending_category_descriptions', $pending_categories); return; } // Check if AI Helper is available if (!class_exists('AIAutotool_AI_Helper') || !AIAutotool_AI_Helper::is_available()) { // Put back and try later array_unshift($pending_categories, $category_id); update_option('aiautotool_pending_category_descriptions', $pending_categories); return; } // Generate description $prompt = $this->build_description_prompt($category); $messages = array( array( 'role' => 'system', 'content' => __('You are an SEO expert. Generate a concise, SEO-optimized description for a WordPress category. The description should be informative, keyword-rich, and between 100-200 words. Return ONLY the description text, no other text or formatting.', 'ai-auto-tool') ), array( 'role' => 'user', 'content' => $prompt ) ); $result = AIAutotool_AI_Helper::chat($messages, array( 'temperature' => 0.7, 'max_tokens' => 300 )); if ($result['success']) { $description = trim($result['content']); $description = preg_replace('/```[\s\S]*?```/', '', $description); $description = trim($description); // Save description wp_update_term($category_id, $taxonomy, array( 'description' => $description )); } // Update pending list update_option('aiautotool_pending_category_descriptions', $pending_categories); // Update completed list if ($result['success']) { $completed = get_option('aiautotool_completed_category_descriptions', array()); $completed[] = array( 'category_id' => $category_id, 'taxonomy' => $taxonomy, 'completed_at' => current_time('mysql') ); update_option('aiautotool_completed_category_descriptions', $completed); } // Save completed category info if ($result['success']) { $completed_categories = get_option('aiautotool_completed_category_descriptions', array()); $completed_categories[] = array( 'id' => $category_id, 'name' => $category->name, 'taxonomy' => $taxonomy, 'completed_time' => current_time('mysql') ); // Keep only last 50 completed if (count($completed_categories) > 50) { $completed_categories = array_slice($completed_categories, -50); } update_option('aiautotool_completed_category_descriptions', $completed_categories); } } /** * AJAX: Get cron job status */ public function ajax_get_cron_status() { check_ajax_referer('aiautotool_auto_categories_nonce', 'nonce'); if (!current_user_can('manage_options')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } $taxonomy = isset($_POST['taxonomy']) ? sanitize_text_field($_POST['taxonomy']) : 'category'; $pending_ids = get_option('aiautotool_pending_category_descriptions', array()); $pending_data = get_option('aiautotool_pending_category_descriptions_data', array()); $completed = get_option('aiautotool_completed_category_descriptions', array()); // Filter by taxonomy $pending_categories = array(); $completed_categories = array(); $next_category = null; // Get pending categories for this taxonomy foreach ($pending_ids as $index => $cat_id) { $cat_taxonomy = isset($pending_data[$cat_id]) ? $pending_data[$cat_id] : 'category'; if ($cat_taxonomy !== $taxonomy) { continue; } $category = get_term($cat_id, $taxonomy); if ($category && !is_wp_error($category)) { $cat_info = array( 'id' => $cat_id, 'name' => $category->name, 'slug' => $category->slug, 'taxonomy' => $taxonomy, 'position' => $index + 1 ); $pending_categories[] = $cat_info; // First one is next to process if ($next_category === null) { $next_category = $cat_info; } } } // Get completed categories for this taxonomy foreach ($completed as $item) { if (isset($item['taxonomy']) && $item['taxonomy'] === $taxonomy) { $cat_id = isset($item['category_id']) ? $item['category_id'] : (isset($item['id']) ? $item['id'] : 0); if ($cat_id > 0) { $category = get_term($cat_id, $taxonomy); if ($category && !is_wp_error($category)) { $completed_categories[] = array( 'id' => $cat_id, 'name' => $category->name, 'slug' => $category->slug ); } } } } // Check if cron is scheduled $cron_scheduled = wp_next_scheduled('aiautotool_auto_write_category_descriptions'); $next_run = ''; if ($cron_scheduled) { $next_run = date_i18n(get_option('date_format') . ' ' . get_option('time_format'), $cron_scheduled); } wp_send_json_success(array( 'has_pending' => !empty($pending_categories), 'pending' => $pending_categories, 'completed' => $completed_categories, 'next_category' => $next_category, 'cron_active' => (bool)$cron_scheduled, 'cron_scheduled' => (bool)$cron_scheduled, 'next_run' => $next_run, 'pending_count' => count($pending_categories), 'completed_count' => count($completed_categories), 'total_pending' => count($pending_categories), 'total_completed' => count($completed_categories) )); } } }