load_options(); $this->init_hooks(); $this->llm_service = new LLM_Service(); } /** * Initialize WordPress hooks. */ private function init_hooks() { // Replace page load generation with cached excerpt display add_filter('the_excerpt', array($this, 'display_cached_excerpt'), 10); add_filter('get_the_excerpt', array($this, 'display_cached_excerpt'), 10); // Generate excerpts on post save add_action('save_post', array($this, 'generate_excerpt_on_save'), 10, 2); add_action('transition_post_status', array($this, 'handle_post_status_change'), 10, 3); // Background processing hooks add_action('ai_smart_excerpt_generate', array($this, 'generate_excerpt_background'), 10, 2); add_action('ai_smart_excerpt_bulk_process', array($this, 'process_bulk_excerpts')); // Admin hooks if (is_admin()) { new AI_Smart_Excerpt_Admin(); } // Load text domain add_action('plugins_loaded', array($this, 'load_textdomain')); } /** * Load plugin options. */ private function load_options() { $defaults = array( 'is_active' => false, 'admin_only' => false, 'llm_provider' => 'claude', 'claude_model' => 'claude-3-5-haiku-20241022', 'openai_model' => 'gpt-4o', 'gemini_model' => 'gemini-1.5-flash', 'api_key' => '', 'excerpt_type' => 'seo', 'max_length' => 300, 'min_content_length' => 100, 'featured_image' => false, 'featured_size' => 'thumbnail', 'featured_align' => 'alignleft', 'search_featured' => false, 'more_link_text' => '', 'skip_manual' => false, 'fallback_enabled' => true, 'background_processing' => true, 'immediate_threshold' => 1000, // Process immediately if content < 1000 chars 'batch_size' => 5, // Process 5 posts per batch 'batch_delay' => 300, // 5 minutes between batches ); $this->options = wp_parse_args(get_option('ai_smart_excerpt_options', array()), $defaults); } /** * Display cached AI excerpt or fallback. * * @param string $excerpt Current excerpt. * @return string Generated excerpt. */ public function display_cached_excerpt($excerpt = '') { global $post; // Return early if conditions not met if (!$this->should_process_post($post)) { return $excerpt; } // Get AI excerpt from post meta $ai_excerpt = get_post_meta($post->ID, '_ai_smart_excerpt', true); if (!empty($ai_excerpt)) { return $this->format_excerpt($ai_excerpt, $post); } // If no AI excerpt exists and we have manual excerpt, use it if (!empty($post->post_excerpt) && !$this->options['skip_manual']) { return $post->post_excerpt; } // Generate fallback excerpt immediately (fast) if ($this->options['fallback_enabled']) { $fallback = $this->fallback_excerpt($post); if (!empty($fallback)) { return $this->format_excerpt($fallback, $post); } } return $excerpt; } /** * Generate excerpt when post is saved. * * @param int $post_id Post ID. * @param WP_Post $post Post object. */ public function generate_excerpt_on_save($post_id, $post) { // Avoid infinite loops and autosaves if (wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) { return; } // Only process published posts if ($post->post_status !== 'publish') { return; } // Check if we should process this post if (!$this->should_process_post($post)) { return; } // Skip if manual excerpt exists and we don't want to override if (!empty($post->post_excerpt) && !$this->options['skip_manual']) { return; } // Check if content has changed (to avoid regenerating on minor updates) $content_hash = md5($post->post_content . $post->post_title); $stored_hash = get_post_meta($post_id, '_ai_excerpt_content_hash', true); if ($content_hash === $stored_hash) { return; // Content hasn't changed } // For immediate processing (small posts or high priority) if ($this->should_process_immediately($post)) { $this->generate_excerpt_immediately($post_id); } else { // Schedule background processing $this->schedule_excerpt_generation($post_id); } // Update content hash update_post_meta($post_id, '_ai_excerpt_content_hash', $content_hash); } /** * Handle post status changes (for scheduled posts). * * @param string $new_status New post status. * @param string $old_status Old post status. * @param WP_Post $post Post object. */ public function handle_post_status_change($new_status, $old_status, $post) { // When a scheduled post becomes published if ($new_status === 'publish' && $old_status !== 'publish') { $this->generate_excerpt_on_save($post->ID, $post); } } /** * Generate excerpt immediately (synchronous). * * @param int $post_id Post ID. */ private function generate_excerpt_immediately($post_id) { $post = get_post($post_id); if (!$post) { return; } $content = $this->prepare_content($post); if (empty($content)) { return; } // Generate AI excerpt $ai_excerpt = $this->llm_service->generate_excerpt( $content, $post->post_title, $this->options['excerpt_type'], $this->options['max_length'] ); // Fallback if AI fails if (!$ai_excerpt && $this->options['fallback_enabled']) { $ai_excerpt = $this->fallback_excerpt($post); } // Store the excerpt if ($ai_excerpt) { update_post_meta($post_id, '_ai_smart_excerpt', $ai_excerpt); update_post_meta($post_id, '_ai_excerpt_generated_at', current_time('timestamp')); } } /** * Schedule excerpt generation in background. * * @param int $post_id Post ID. */ private function schedule_excerpt_generation($post_id) { // Schedule single event for this post if (!wp_next_scheduled('ai_smart_excerpt_generate', array($post_id, false))) { wp_schedule_single_event( time() + 30, // Process in 30 seconds 'ai_smart_excerpt_generate', array($post_id, false) ); } } /** * Generate excerpt in background (WordPress Cron). * * @param int $post_id Post ID. * @param bool $force Force regeneration even if excerpt exists. */ public function generate_excerpt_background($post_id, $force = false) { $post = get_post($post_id); if (!$post) { return; } // Skip if excerpt already exists and not forcing if (!$force && get_post_meta($post_id, '_ai_smart_excerpt', true)) { return; } // Add a small delay to avoid API rate limits if (!$force) { sleep(1); } $this->generate_excerpt_immediately($post_id); } /** * Check if we should process this post. * * @param WP_Post $post Post object. * @return bool */ private function should_process_post($post) { // Plugin not active if (!$this->options['is_active']) { return false; } // Admin only mode if ($this->options['admin_only'] && !is_admin()) { return false; } // Only process posts and pages if (!in_array($post->post_type, array('post', 'page'))) { return false; } // Must be published if ($post->post_status !== 'publish') { return false; } // Check if post has enough content $content = strip_shortcodes($post->post_content); $content_length = strlen(wp_strip_all_tags($content)); if ($content_length < $this->options['min_content_length']) { return false; } return true; } /** * Check if we should process immediately vs background. * * @param WP_Post $post Post object. * @return bool */ private function should_process_immediately($post) { // Always process immediately in admin if (is_admin()) { return true; } // Process small posts immediately $content_length = strlen(wp_strip_all_tags($post->post_content)); if ($content_length < 1000) { return true; } // Check if we have less than 5 pending background jobs $pending_jobs = wp_count_scheduled_hooks('ai_smart_excerpt_generate'); if ($pending_jobs < 5) { return true; } return false; } /** * Bulk process excerpts for existing posts. */ public function process_bulk_excerpts() { // Get current progress $bulk_progress = get_option('ai_smart_excerpt_bulk_progress', array( 'status' => 'idle', 'total' => 0, 'processed' => 0, 'current_batch' => 0, 'errors' => 0, 'started_at' => 0 )); // If this is the first run, initialize the progress if ($bulk_progress['status'] === 'idle') { // Count total posts needing excerpts using more efficient query global $wpdb; $total_count = $wpdb->get_var($wpdb->prepare(" SELECT COUNT(DISTINCT p.ID) FROM {$wpdb->posts} p LEFT JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id AND pm.meta_key = '_ai_smart_excerpt' WHERE p.post_type IN ('post', 'page') AND p.post_status = 'publish' AND (pm.meta_value IS NULL OR pm.meta_value = '') ")); $bulk_progress = array( 'status' => 'running', 'total' => (int) $total_count, 'processed' => 0, 'current_batch' => 1, 'errors' => 0, 'started_at' => time(), 'last_updated' => time() ); update_option('ai_smart_excerpt_bulk_progress', $bulk_progress); // If no posts to process, mark as completed immediately if ($total_count == 0) { $bulk_progress['status'] = 'completed'; $bulk_progress['completed_at'] = time(); update_option('ai_smart_excerpt_bulk_progress', $bulk_progress); return; } } // Get posts to process in this batch using more efficient query global $wpdb; $batch_size = 5; $offset = ($bulk_progress['current_batch'] - 1) * $batch_size; $post_ids = $wpdb->get_col($wpdb->prepare(" SELECT DISTINCT p.ID FROM {$wpdb->posts} p LEFT JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id AND pm.meta_key = '_ai_smart_excerpt' WHERE p.post_type IN ('post', 'page') AND p.post_status = 'publish' AND (pm.meta_value IS NULL OR pm.meta_value = '') ORDER BY p.ID ASC LIMIT %d OFFSET %d ", $batch_size, $offset)); $processed_in_batch = 0; $errors_in_batch = 0; foreach ($post_ids as $post_id) { $post = get_post($post_id); if ($post && $this->should_process_post($post)) { try { $this->generate_excerpt_immediately($post->ID); $processed_in_batch++; // Update progress after each post $bulk_progress['processed']++; $bulk_progress['last_updated'] = time(); update_option('ai_smart_excerpt_bulk_progress', $bulk_progress); // Small delay to avoid API rate limits sleep(2); } catch (Exception $e) { $errors_in_batch++; $bulk_progress['errors']++; $bulk_progress['last_updated'] = time(); update_option('ai_smart_excerpt_bulk_progress', $bulk_progress); } } } // Update final batch progress $bulk_progress['current_batch']++; $bulk_progress['last_updated'] = time(); // Check if there are more posts to process $remaining_posts = $wpdb->get_var($wpdb->prepare(" SELECT COUNT(DISTINCT p.ID) FROM {$wpdb->posts} p LEFT JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id AND pm.meta_key = '_ai_smart_excerpt' WHERE p.post_type IN ('post', 'page') AND p.post_status = 'publish' AND (pm.meta_value IS NULL OR pm.meta_value = '') AND p.ID > %d ", max($post_ids ?: array(0)))); // Schedule next batch if there are more posts if ($remaining_posts > 0 && count($post_ids) > 0) { wp_schedule_single_event( time() + 60, // Wait 1 minute between batches 'ai_smart_excerpt_bulk_process' ); update_option('ai_smart_excerpt_bulk_progress', $bulk_progress); } else { // Mark as completed $bulk_progress['status'] = 'completed'; $bulk_progress['completed_at'] = time(); update_option('ai_smart_excerpt_bulk_progress', $bulk_progress); } } /** * Prepare content for AI processing. * * @param WP_Post $post Post object. * @return string Cleaned content. */ public function prepare_content($post) { $content = $post->post_content; // Remove shortcodes $content = strip_shortcodes($content); // Remove HTML tags $content = wp_strip_all_tags($content); // Clean up whitespace $content = preg_replace('/\s+/', ' ', $content); $content = trim($content); // Limit content length for API efficiency (keep first 3000 chars) if (strlen($content) > 3000) { $content = substr($content, 0, 3000) . '...'; } return $content; } /** * Format the final excerpt with images and links. * * @param string $excerpt Generated excerpt. * @param WP_Post $post Post object. * @return string Formatted excerpt. */ private function format_excerpt($excerpt, $post) { $output = ''; // Add featured image if enabled if ($this->options['featured_image']) { $image = $this->get_featured_image($post); if ($image) { $output .= $image; } } // Add the excerpt text $output .= '

' . esc_html($excerpt) . '

'; // Add more link if configured if (!empty($this->options['more_link_text'])) { $more_link = sprintf( ' %s', esc_url(get_permalink($post)), esc_html($this->options['more_link_text']) ); $output .= $more_link; } return $output; } /** * Get featured image HTML. * * @param WP_Post $post Post object. * @return string Image HTML or empty string. */ private function get_featured_image($post) { if (has_post_thumbnail($post->ID)) { return get_the_post_thumbnail( $post->ID, $this->options['featured_size'], array('class' => $this->options['featured_align']) ); } // Search for first image in content if enabled if ($this->options['search_featured']) { $image_url = $this->extract_first_image($post); if ($image_url) { return sprintf( '%s', esc_url(get_permalink($post)), esc_url($image_url), esc_attr($this->options['featured_align']), esc_attr(get_the_title($post)) ); } } return ''; } /** * Extract first image from post content. * * @param WP_Post $post Post object. * @return string|false Image URL or false. */ private function extract_first_image($post) { $content = $post->post_content; if (stripos($content, 'post_content; $original_excerpt = $post->post_excerpt; // Clear any existing excerpt to force WordPress to generate from content $post->post_excerpt = ''; $post->post_content = $original_content; // Use WordPress's built-in excerpt generation $excerpt = wp_trim_excerpt('', $post); // Restore original values $post->post_content = $original_content; $post->post_excerpt = $original_excerpt; return $excerpt; } /** * Load plugin text domain. * Note: Since WordPress 4.6+, textdomain loading is handled automatically * for plugins hosted on WordPress.org. */ public function load_textdomain() { // Automatic textdomain loading since WordPress 4.6+ // No manual load_plugin_textdomain() call needed } /** * Plugin activation. */ public static function activate() { // Set default options $defaults = array( 'is_active' => false, 'llm_provider' => 'claude', 'excerpt_type' => 'seo', 'max_length' => 300, ); add_option('ai_smart_excerpt_options', $defaults); // Clear any existing caches wp_cache_flush(); } /** * Plugin deactivation. */ public static function deactivate() { // Clean up known transients - WordPress will handle the cleanup // Common transient patterns used by this plugin $transient_patterns = array( 'ai_excerpt_cache_', 'ai_excerpt_response_', 'ai_excerpt_settings_', 'ai_excerpt_status_' ); // Attempt to delete common transients foreach ($transient_patterns as $pattern) { for ($i = 0; $i < 1000; $i++) { $transient_name = $pattern . $i; delete_transient($transient_name); } } // Clear object cache wp_cache_flush(); } /** * Get plugin options. * * @return array Plugin options. */ public function get_options() { return $this->options; } /** * Update plugin options. * * @param array $options New options. */ public function update_options($options) { $this->options = wp_parse_args($options, $this->options); update_option('ai_smart_excerpt_options', $this->options); } }