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( '/
\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', '
' . $answer . '
\s*<\/p>/', '', $new_content ); $new_content = preg_replace( '/
\s*(.*?)<\/strong>\s*(.*?)<\/p>/is',
$faq_html,
$matches,
PREG_SET_ORDER
);
// No encontró preguntas
if (empty($matches)) {
return '';
}
$faq_items = [];
foreach ($matches as $faq) {
$question = trim(wp_strip_all_tags($faq[1]));
$answer = trim(wp_strip_all_tags($faq[2]));
// Ignorar vacíos
if (empty($question) || empty($answer)) {
continue;
}
// Evitar Quick Answer
if (
stripos($question, 'Respuesta rápida') !== false ||
stripos($question, 'Quick Answer') !== false
) {
continue;
}
$faq_items[] = [
"@type" => "Question",
"name" => $question,
"acceptedAnswer" => [
"@type" => "Answer",
"text" => $answer
]
];
}
// Sin FAQs válidas
if (empty($faq_items)) {
return '';
}
$schema = [
"@context" => "https://schema.org",
"@type" => "FAQPage",
"mainEntity" => $faq_items
];
return '';
}function mre_generate_article_schema($keyword, $language = 'es') {
$schema = [
"@context" => "https://schema.org",
"@type" => "MedicalWebPage",
"headline" => $keyword,
"name" => $keyword,
"inLanguage" => $language,
"about" => [
"@type" => "MedicalCondition",
"name" => $keyword
],
"publisher" => [
"@type" => "Organization",
"name" => get_bloginfo('name')
]
];
return '';
}
add_action('init', function() {
remove_filter('the_content', 'wpautop');
remove_filter('the_excerpt', 'wpautop');
remove_filter('the_content', 'wptexturize');
remove_filter('the_excerpt', 'wptexturize');
}, 99);
add_action('wp_head', 'mre_global_styles');function mre_wrap_template($keyword, $content, $post_id, $category_id = null, $language = 'es') {
$cta_link = mre_get_cta_link($post_id, $category_id);
// =========================
// TEXTOS MULTILENGUAJE
// =========================
if ($language === 'en') {
// Intro headline más editorial (NO H1 duplicado)
$intro_headline = "Digestive discomfort like {$keyword} may affect your daily wellbeing and digestion.";
$subtitle = "Simple practical strategies that may help reduce this issue naturally and effectively.";
$social = "✔ Over 2,000 people have used similar digestive support solutions";
$cta_top = "See recommended option";
$solution_title = "Recommended digestive support";
$benefits = "✔ Helps support digestive comfort
{$subtitle}
{$social}
{$warning}
\s*(
✔ May reduce bloating and discomfort
✔ Easy daily support";
$warning = "If symptoms continue or worsen, consulting a healthcare professional is recommended.";
$cta_bottom = "Discover digestive support options";
} else {
// Intro headline más editorial (NO H1 duplicado)
$intro_headline = "Las molestias digestivas como {$keyword} pueden afectar el descanso y la digestión.";
$subtitle = "Estrategias prácticas que pueden ayudar a reducir este problema digestivo de forma natural.";
$social = "✔ Más de 2,000 personas han utilizado soluciones digestivas similares";
$cta_top = "Ver opción recomendada";
$solution_title = "Apoyo digestivo recomendado";
$benefits = "✔ Ayuda a mejorar el confort digestivo
✔ Puede reducir gases e inflamación
✔ Fácil de incorporar diariamente";
$warning = "Si los síntomas continúan o empeoran, es recomendable consultar con un profesional de salud.";
$cta_bottom = "Descubrir opciones digestivas";
}
// =========================
// CTA DINÁMICO CON VARIACIONES
// =========================
if ($language === 'en') {
switch ($category_id) {
// Acid reflux
case 587:
$cta_variations = [
"See the recommended option for acid reflux relief",
"Discover the digestive option recommended for heartburn",
"See what may help reduce acid reflux naturally",
"Explore the recommended solution for reflux symptoms"
];
break;
// Constipation
case 588:
$cta_variations = [
"See the recommended option to improve bowel regularity",
"Discover the digestive support option recommended for constipation",
"See what may help support healthy digestion",
"Explore the recommended solution for digestive regularity"
];
break;
// Gas & bloating
case 589:
$cta_variations = [
"See the recommended option to reduce bloating and gas",
"Discover the digestive option recommended for bloating",
"See what may help relieve abdominal discomfort",
"Explore the recommended solution for gas and bloating"
];
break;
default:
$cta_variations = [
"See the recommended option for digestive relief",
"Discover the recommended digestive support option",
"Explore the digestive solution recommended for this issue"
];
break;
}
} else {
switch ($category_id) {
// Acidez y reflujo
case 587:
$cta_variations = [
"Ver opción recomendada para aliviar la acidez",
"Descubrir alternativa digestiva recomendada para el reflujo",
"Ver solución recomendada para reducir la acidez",
"Conocer opción digestiva recomendada para el ardor"
];
break;
// Estreñimiento y tránsito
case 588:
$cta_variations = [
"Ver opción recomendada para mejorar el tránsito intestinal",
"Descubrir alternativa digestiva recomendada para el estreñimiento",
"Ver solución recomendada para mejorar la digestión",
"Conocer opción recomendada para apoyar la regularidad intestinal"
];
break;
// Gases e inflamación
case 589:
$cta_variations = [
"Ver opción recomendada para reducir los gases y la inflamación",
"Descubrir alternativa digestiva recomendada para la hinchazón",
"Ver solución recomendada para aliviar molestias digestivas",
"Conocer opción recomendada para disminuir la inflamación abdominal"
];
break;
default:
$cta_variations = [
"Ver opción recomendada para aliviar este problema digestivo",
"Descubrir solución digestiva recomendada",
"Conocer alternativa recomendada para apoyar la digestión"
];
break;
}
}
// CTA aleatorio
$cta_main = $cta_variations[array_rand($cta_variations)];
// =========================
// SCHEMA
// =========================
$faq_schema = mre_generate_faq_schema($content);
$article_schema = mre_generate_article_schema($keyword, $language);
// =========================
// TEMPLATE FINAL
// =========================
return "
{$solution_title}