'; 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') . '