function mre_generate_post( $keyword, $category_id = null, $language = 'es', $post_status = 'draft' ) { $api_key = get_option('mre_api_key'); // ========================= // PROMPT MULTILENGUAJE // ========================= if ($language === 'en') { $prompt = "You are a medical content writer specialized in digestive health and AI-optimized SEO. Write a practical, clear, highly structured article about: {$keyword} IMPORTANT RULES: - Write naturally for humans first - Optimize for Google AI Overviews, Gemini, Perplexity and ChatGPT Search - Use short paragraphs - Use semantic headings - Avoid fluff - Avoid fake medical claims - Use conversational language - Keep readability very high - Prioritize direct answers STRUCTURE: ## Quick Answer Directly answer the problem in 2-3 sentences. ## What may cause it Explain possible causes. ## How to relieve it Include a practical bullet list. ## What to avoid Include another bullet list. ## When to worry Explain warning signs. ## Frequently Asked Questions Include 5 FAQ questions and answers. FORMAT RULES: - Use markdown H2 with ## - Use markdown lists with - - FAQ questions MUST use: **Question** Answer Do NOT use tables. Do NOT use code blocks. "; } else { $prompt = "Eres un redactor especializado en salud digestiva y SEO optimizado para IA. Escribe un artículo práctico, claro y altamente estructurado sobre: {$keyword} REGLAS IMPORTANTES: - Escribe natural para humanos primero - Optimiza para Google AI Overviews, Gemini, Perplexity y ChatGPT Search - Usa párrafos cortos - Usa headings semánticos - Evita relleno - Evita claims médicos falsos - Usa lenguaje conversacional - Mantén alta legibilidad - Prioriza respuestas directas ESTRUCTURA: ## Respuesta rápida Responde directamente el problema en 2-3 frases. ## Qué puede causarlo Explica posibles causas. ## Cómo aliviarlo Incluye lista práctica con bullets. ## Qué evitar Incluye otra lista. ## Cuándo preocuparse Explica señales de alerta. ## Preguntas frecuentes Incluye 5 preguntas frecuentes con respuestas. REGLAS DE FORMATO: - Usa H2 markdown con ## - Usa listas markdown con - - Las preguntas FAQ DEBEN usar: **Pregunta** Respuesta NO uses tablas. NO uses bloques de código. "; } // ========================= // OPENAI REQUEST // ========================= $response = wp_remote_post( 'https://api.openai.com/v1/chat/completions', [ 'headers' => [ 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', ], 'body' => json_encode([ 'model' => 'gpt-4.1-mini', 'messages' => [ [ 'role' => 'user', 'content' => $prompt ] ], 'temperature' => 0.7 ]), 'timeout' => 120, ] ); // ========================= // VALIDAR RESPONSE // ========================= if (is_wp_error($response)) { return false; } $body = json_decode( wp_remote_retrieve_body($response), true ); if ( !isset($body['choices'][0]['message']['content']) ) { return false; } // ========================= // CONTENIDO IA // ========================= $content = $body['choices'][0]['message']['content']; // Links markdown → HTML $content = mre_convert_markdown_links($content); // Markdown → HTML limpio $content = mre_clean_markdown($content); // Quick Answer block $content = mre_extract_quick_answer($content, $language); // Limpiar H2 sobrantes $content = preg_replace( '/

Respuesta rápida\s*<\/h2>/i', '', $content ); $content = preg_replace( '/

Quick Answer\s*<\/h2>/i', '', $content ); // Limpiar párrafos vacíos $content = preg_replace( '/

\s*<\/p>/', '', $content ); // Balancear HTML $content = force_balance_tags($content); // Evitar doble wpautop remove_filter('the_content', 'wpautop'); remove_filter('the_excerpt', 'wpautop'); // ========================= // WRAPPER FINAL // ========================= $final_content = mre_wrap_template( $keyword, $content, 0, $category_id, $language ); // ========================= // EXCERPT SEO // ========================= $excerpt = wp_strip_all_tags($content); $excerpt = html_entity_decode($excerpt); $excerpt = preg_replace('/\s+/', ' ', $excerpt); $excerpt = trim($excerpt); $excerpt = mb_substr($excerpt, 0, 155) . '...'; // ========================= // INSERT POST // ========================= $post_id = wp_insert_post([ 'post_title' => ucfirst($keyword), 'post_content' => $final_content, 'post_status' => $post_status, 'post_type' => 'post', 'post_excerpt' => $excerpt, 'post_category'=> [$category_id] ]); // ========================= // ACTUALIZAR CTA // ========================= if ($post_id) { $updated_content = mre_wrap_template( $keyword, $content, $post_id, $category_id, $language ); wp_update_post([ 'ID' => $post_id, 'post_content' => $updated_content ]); } return $post_id; }function mre_clean_markdown($content) { // ========================= // LIMPIAR // ========================= $content = trim($content); $content = str_replace("\r\n", "\n", $content); // ========================= // HEADINGS // ========================= $content = preg_replace( '/^##\s*(.*?)\s*$/m', '

$1

', $content ); $content = preg_replace( '/^###\s*(.*?)\s*$/m', '

$1

', $content ); // ========================= // FAQ STRUCTURE // ========================= $content = preg_replace_callback( '/^\*\*(.+?)\*\*\s*\n(.+?)(?=\n\*\*|\n

|$)/ms', function($matches) { $question = trim($matches[1]); $answer = trim($matches[2]); return '

' . $question . '

' . $answer . '

'; }, $content ); // ========================= // BOLD NORMAL // ========================= $content = preg_replace( '/\*\*(.*?)\*\*/', '$1', $content ); // ========================= // LISTAS MARKDOWN → HTML // ========================= $content = preg_replace_callback( '/((?:^\- .*$(?:\n|$))+)/m', function($matches) { $items = explode("\n", trim($matches[1])); $html = ''; return $html; }, $content ); // ========================= // PÁRRAFOS // ========================= $blocks = preg_split('/(

.*?<\/h2>|