Files
feadulta/scripts/remap_carta_tr_links.php
T

41 lines
2.0 KiB
PHP

<?php
// Remapea los enlaces internos de las traducciones de una carta: convierte
// permalinks/IDs que apuntan al artículo ES → permalink del artículo en el
// idioma de CADA carta (vía Polylang). Necesario cuando la carta ES se tradujo
// DESPUÉS de haberle fijado los enlaces a permalink (las traducciones heredan
// los permalinks ES). Solo toca traducciones (no la ES). Dry-run por defecto.
require getenv('FEA_WP_LOAD') ?: '/var/www/html/wp-load.php';
global $wpdb;
$APPLY = getenv("APPLY") === "1";
$BAK = "/tmp/remap_carta_tr_bak"; if ($APPLY) @mkdir($BAK,0777,true);
$CARTA = (int)(getenv("CARTA") ?: 53644);
$tr = pll_get_post_translations($CARTA);
$tot = 0;
foreach($tr as $lang=>$pid){
if($lang === 'es') continue; // la ES ya está bien
$post = get_post($pid); if(!$post) continue;
$chg=0; $miss=[];
$new = preg_replace_callback('~href="([^"]+)"~i', function($m) use($lang,&$chg,&$miss){
$href = html_entity_decode(trim($m[1]));
if(stripos($href,'farmer.taild3aaf6.ts.net')===false && stripos($href,'/fea/')===false) return $m[0];
$es = 0;
if(preg_match('~[?&]p=(\d+)~',$href,$mm)) $es=(int)$mm[1]; // forma ?p=ID
if(!$es) $es = (int)url_to_postid($href); // forma /slug/
if(!$es){ return $m[0]; }
if(pll_get_post_language($es) !== 'es'){ return $m[0]; } // solo si apunta a ES
$t = pll_get_post($es,$lang);
if(!$t || $t==$es){ $miss[]=$href; return $m[0]; } // sin traducción → dejar
$url = get_permalink($t);
if(!$url) return $m[0];
$chg++;
return 'href="'.esc_url($url).'"';
}, $post->post_content);
echo sprintf("#%d [%s] «%s» — %d remapeados%s\n",$pid,$lang,mb_substr($post->post_title,0,30),$chg,
$miss?(" | sin traducción: ".count($miss)):"");
$tot+=$chg;
if($APPLY && $chg){ file_put_contents("$BAK/$pid.html",$post->post_content);
$wpdb->update($wpdb->posts,['post_content'=>$new],['ID'=>$pid]); clean_post_cache($pid); }
}
echo ($APPLY?"APLICADO":"DRY-RUN").": $tot enlaces.\n";