refactorizar

This commit is contained in:
2025-10-14 15:08:21 +00:00
parent d1e5638ed2
commit 4abf91910f
10 changed files with 367 additions and 349 deletions

View File

@@ -44,39 +44,6 @@ class StarterSite extends Site {
}
});
//Arreglar paginación para post type "opinion"
add_action('init', function() {
// Asegurarse de que opinion tenga archive habilitado
global $wp_post_types;
if (isset($wp_post_types['opinion'])) {
$wp_post_types['opinion']->has_archive = true;
}
});
//Añadir regla de rewrite personalizada para paginación de "opinion"
add_action('init', function() {
add_rewrite_rule(
'^opinion/page/([0-9]{1,})/?$',
'index.php?post_type=opinion&paged=$matches[1]',
'top'
);
// Si usas multiidioma, añade también para cada idioma
add_rewrite_rule(
'^([a-z]{2})/opinion/page/([0-9]{1,})/?$',
'index.php?lang=$matches[1]&post_type=opinion&paged=$matches[2]',
'top'
);
}, 10);
//Forzar flush de rewrite rules (solo una vez)
add_action('init', function() {
if (get_option('opinion_pagination_flushed') !== 'yes') {
flush_rewrite_rules();
update_option('opinion_pagination_flushed', 'yes');
}
}, 999);
/** POST "QUÉ ES LA CNT" */
// Previene borrar el post "Qué es la cnt" porque forma parte del menú //
$ids_especiales = [10982, 4791, 10981];
@@ -291,80 +258,73 @@ class StarterSite extends Site {
return $file_types;
}
//section "portada> ENLACES"
private function getBotonesEnlaces($page_id = null) {
// Añadir idiomas de Polylang
private function getPolylangData() {
$polylang_data = array();
if (function_exists('pll_the_languages')) {
// Idiomas con toda la información
$polylang_data['languages'] = pll_the_languages(array(
'raw' => 1,
'hide_if_no_translation' => 0,
'show_flags' => 1,
'show_names' => 1
));
// Información del idioma actual
$polylang_data['current_language'] = pll_current_language();
$polylang_data['current_language_name'] = pll_current_language('name');
$polylang_data['default_language'] = pll_default_language();
if (is_null($page_id)) {
$page_id = get_the_ID();
// Si estamos en euskera, obtener la página en español
if (pll_current_language() == 'eu') {
$spanish_page_id = pll_get_post($page_id, 'es');
$page_id = $spanish_page_id ?: $page_id;
// DEBUG: Escribir en el log de errores
//error_log('Languages: ' . print_r($polylang_data['languages'], true));
//error_log('Current language: ' . $polylang_data['current_language']);
//error_log('Default language: ' . $polylang_data['default_language']);
// URLs de home para cada idioma
$polylang_data['home_urls'] = array();
foreach ($polylang_data['languages'] as $lang) {
$polylang_data['home_urls'][$lang['slug']] = $lang['url'];
}
}
$botones = [];
for ($i = 1; $i <= 4; $i++) {
$imagen = get_field('imagen_boton_' . $i, $page_id);
$enlace = get_field('enlace_boton_' . $i, $page_id);
$botones[] = [
'imagen' => $imagen,
'enlace' => $enlace,
];
}
return $botones;
return $polylang_data;
}
//Get POSTS with category "noticias"
private function getPostsNews() {
/* TEMP. DELETE... */
private function getAllPostsNews() {
$post = Timber::get_post();
//if ($post) { error_log('✅ Este es el ID Página news: ' . $post->ID);}
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// $post = Timber::get_post();
// //if ($post) { error_log('✅ Este es el ID Página news: ' . $post->ID);}
// $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
//84=portada CAST & 331= portada EUSKARA
if ( $post && ( $post->ID === 84 || $post->ID === 331) ) {
return [
'posts' => Timber::get_posts([
'post_type' => 'post',
'posts_per_page' => -1,
'category_name' => 'noticias',
'post_status' => 'publish'
]),
'pagination' => null
];
//8=noticias CAST & 339= noticias EUSKARA
} elseif ( $post && ( $post->ID === 8 || $post->ID === 339) ) {
global $wp_query;
$temp_query = $wp_query;
$wp_query = new \WP_Query([
'post_type' => 'post',
'category_name' => 'noticias',
'posts_per_page' => 10,
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC',
'paged' => $paged,
]);
// //8=noticias CAST & 339= noticias EUSKARA
// if ( $post && ( $post->ID === 8 || $post->ID === 339) ) {
// global $wp_query;
// $temp_query = $wp_query;
// $wp_query = new \WP_Query([
// 'post_type' => 'post',
// 'category_name' => 'noticias',
// 'posts_per_page' => 10,
// 'post_status' => 'publish',
// 'orderby' => 'date',
// 'order' => 'DESC',
// 'paged' => $paged,
// ]);
$posts = Timber::get_posts(); // Lee de la query global que acabamos de crear
$pagination = new \Timber\Pagination();
$wp_query = $temp_query; // Restaurar query original
// $posts = Timber::get_posts(); // Lee de la query global que acabamos de crear
// $pagination = new \Timber\Pagination();
// $wp_query = $temp_query; // Restaurar query original
return $posts;
// return $posts;
// }
}
//error_log('❌ getPostsNews - No coincide con ninguna página');
return [
'posts' => [],
'pagination' => null
];
// //error_log('❌ getPostsNews - No coincide con ninguna página');
// return [
// 'posts' => [],
// 'pagination' => null
// ];
}
private function getIconsRRSS() {
@@ -445,123 +405,6 @@ class StarterSite extends Site {
return ['posts' => [], 'pagination' => null];
}
private function getOpinion() {
$post = Timber::get_post();
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
//84=portada CAST & 331= portada EUSKARA
if ( $post && ( $post->ID === 84 || $post->ID === 331) ) {
return Timber::get_posts([
'post_type' => 'opinion',
'posts_per_page' => 1,
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC'
]);
//2011=opinion CAST & 10962=opinion EUSKARA
} elseif ( $post && ($post->ID === 2011 || $post->ID === 10962) ) {
global $wp_query;
$temp_query = $wp_query;
$wp_query = new \WP_Query([
'post_type' => 'opinion',
'posts_per_page' => 10,
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC',
'paged' => $paged,
]);
// Timber::get_posts() SIN PARÁMETROS usa la query global ($wp_query)
$posts = Timber::get_posts(); // Lee de la query global que acabamos de crear
$pagination = new \Timber\Pagination($wp_query->max_num_pages);
$wp_query = $temp_query; // Restaurar query original
return $posts;
}
return ['posts' => [], 'pagination' => null];
}
//Get portada > Campañas
private function getCampanaArticles() {
return Timber::get_posts([
'post_type' => 'campana',
'posts_per_page' => 1,
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC'
]);
}
//Get portada > Conflictos (category)
private function getConflictsCategory() {
return Timber::get_posts([
'post_type' => 'post',
'posts_per_page' => 1,
'post_status' => 'publish',
'category_name' => 'conflictos laborales',
'orderby' => 'date',
'order' => 'DESC'
]);
}
public function generar_embed_universal($url) {
if (empty($url)) {
return false;
}
// YouTube
if (strpos($url, 'youtube.com') !== false || strpos($url, 'youtu.be') !== false) {
//error_log('es un vídeo de youtube'); // Debug
preg_match('/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/', $url, $matches);
if (!empty($matches[1])) {
$embed_data = [
'platform' => 'youtube',
'embed_url' => 'https://www.youtube.com/embed/' . $matches[1] . '?rel=0&modestbranding=1',
'thumbnail_url' => 'https://img.youtube.com/vi/' . $matches[1]. '/hqdefault.jpg',
'allow' => 'autoplay; encrypted-media; picture-in-picture'
];
//error_log('Embed URL generada: ' . $embed_data['embed_url']);
return $embed_data;
} else {
error_log('No se pudo extraer ID de YouTube');
}
}
// Vimeo
if (strpos($url, 'vimeo.com') !== false) {
preg_match('/vimeo\.com\/(\d+)/', $url, $matches);
if (!empty($matches[1])) {
return [
'platform' => 'vimeo',
'embed_url' => 'https://player.vimeo.com/video/' . $matches[1] . '?title=0&byline=0&portrait=0',
'allow' => 'autoplay; fullscreen; picture-in-picture'
];
}
}
// Si no se reconoce la plataforma
return [
'platform' => 'generic',
'embed_url' => $url,
'allow' => 'fullscreen'
];
}
// Hacer función disponible en Twig
public function add_videos_embed_to_twig ($twig) {
//error_log('Añadiendo función generar_embed a Twig'); // Debug
$twig->addFunction(new \Twig\TwigFunction('generar_embed', [$this, 'generar_embed_universal']));
return $twig;
}
private function getPaginasAcerca() {
return Timber::get_posts([
'post_type' => 'acerca',
@@ -572,7 +415,6 @@ class StarterSite extends Site {
]);
}
//Obtiene los "Documentos"
private function getDocumentos() {
$args = ([
@@ -615,7 +457,6 @@ class StarterSite extends Site {
return $documentos;
}
/** Obetiene campos de "Enlaces" */
private function getEnlaces() {
$grupos = [];
@@ -680,9 +521,8 @@ class StarterSite extends Site {
return $grupos;
}
/** Servicios públicos y privados */
private function getSubpaginasServicios() {
//Which paths is for 'servicios'
public function whichPathIs() {
$current_post = get_post();
$slug_actual = $current_post->post_name;
@@ -700,15 +540,38 @@ class StarterSite extends Site {
$path = 'ekintza-sindikala/zerbitzu-pribatuak';
$tipo = 'pribatuak';
} else {
return [
'path' => null,
'tipo' => null,
'found' => false
];
}
return [
'path' => $path,
'tipo' => $tipo,
'found' => true
];
}
/** Servicios públicos y privados */
private function getSubpaginasServicios() {
$pathInfo = $this->whichPathIs();
// Si no encontramos una página válida, retornar vacío
if (!$pathInfo['found']) {
return [
'subpaginas' => [],
'pagination_Servicios' => null
];
}
$pag_servicios = get_page_by_path($path);
$full_path = $pathInfo['path'];
$pag_servicios = get_page_by_path($full_path);
if (!$pag_servicios) {
error_log("🔴 Página '$path' no encontrada.");
error_log("🔴 Página '$pathTipo.$path' no encontrada.");
return [
'subpaginas' => [],
'pagination_Servicios' => null
@@ -734,7 +597,7 @@ class StarterSite extends Site {
$subpaginas = Timber::get_posts(); // Timber::get_posts() SIN PARÁMETROS usa la query global ($wp_query)
foreach ($subpaginas as $pagina) {
$pagina->thumbnail = get_the_post_thumbnail_url($pagina->ID);
$pagina->tipo_servicio = $tipo;
$pagina->tipo_servicio = $pathInfo['tipo'];
}
$pagination = new \Timber\Pagination($wp_query->max_num_pages); // Crear objeto de paginación
@@ -744,7 +607,6 @@ class StarterSite extends Site {
}
//Campos de contactos
public function getContactoFields() {
$post = Timber::get_post();
@@ -769,57 +631,6 @@ class StarterSite extends Site {
}
// Excluir páginas de la búsqueda
public function exclude_pages_from_search($query) {
if (!is_admin() && $query->is_main_query() && $query->is_search()) {
$query->set('meta_query', array(
'relation' => 'OR',
array(
'key' => 'exclude_from_search',
'compare' => 'NOT EXISTS'
),
array(
'key' => 'exclude_from_search',
'value' => '1',
'compare' => '!='
)
));
}
}
// Añadir idiomas de Polylang
private function getPolylangData() {
$polylang_data = array();
if (function_exists('pll_the_languages')) {
// Idiomas con toda la información
$polylang_data['languages'] = pll_the_languages(array(
'raw' => 1,
'hide_if_no_translation' => 0,
'show_flags' => 1,
'show_names' => 1
));
// Información del idioma actual
$polylang_data['current_language'] = pll_current_language();
$polylang_data['current_language_name'] = pll_current_language('name');
$polylang_data['default_language'] = pll_default_language();
// DEBUG: Escribir en el log de errores
//error_log('Languages: ' . print_r($polylang_data['languages'], true));
//error_log('Current language: ' . $polylang_data['current_language']);
//error_log('Default language: ' . $polylang_data['default_language']);
// URLs de home para cada idioma
$polylang_data['home_urls'] = array();
foreach ($polylang_data['languages'] as $lang) {
$polylang_data['home_urls'][$lang['slug']] = $lang['url'];
}
}
return $polylang_data;
}
private function getPostIndustry() {
$pag_industry = get_page_by_path('accion-sindical/industria');
@@ -848,29 +659,203 @@ class StarterSite extends Site {
return $subpaginas;
}
private function getListContacts() {
$contactos_page = Timber::get_posts([
'post_type' => 'page',
'name' => 'kontaktua', // slug en euskera
'posts_per_page' => 1
])[0] ?? null;
// Si no encuentra en euskera, busca en castellano
if (!$contactos_page) {
$contactos_page = Timber::get_posts([
'post_type' => 'page',
'name' => 'contactos', // slug en castellano
'posts_per_page' => 1
])[0] ?? null;
}
return $contactos_page ? Timber::get_posts([
'post_type' => 'page',
'post_parent' => $contactos_page->ID,
'orderby' => 'menu_order',
'order' => 'ASC'
]) : [];
}
//Global variables
public function add_global_context($context) {
// GLobales
$context['logos_header'] = $this->getLogosHeader();
$context['redes_sociales'] = $this->getIconsRRSS();
$context['listContacts'] = $this->getListContacts();
$context['footer_1'] = get_field('footer_text_1', 'option');
$context['footer_2'] = get_field('footer_text_2', 'option');
$context['botones_imagen'] = $this->getBotonesEnlaces();
$context['redes_sociales'] = $this->getIconsRRSS();
$context['logos_header'] = $this->getLogosHeader();
$context['posts_opinion'] = $this->getOpinion();
$context['posts_campana'] = $this->getCampanaArticles();
//Otras páginas
$context['videos'] = $this->getVideos();
$context['paginas_acerca'] = $this->getPaginasAcerca();
$context['posts_conflicts'] = $this->getConflictsCategory();
$context['documentos'] = $this->getDocumentos();
$context['enlaces'] = $this->getEnlaces();
$context['contacto_info'] = $this->getContactoFields();
$context['posts_industry'] = $this->getPostIndustry();
$context['posts_noticias'] = $this->getPostsNews();
$context['subpaginas_servicios'] = $this->getSubpaginasServicios();
$context['videos'] = $this->getVideos();
//otros
$context = array_merge($context, $this->getPolylangData());
return $context;
}
/**
* Funciones public 'Template-Portada'
*/
public function getLastsPostsNews() {
return Timber::get_posts([
'post_type' => 'post',
'category_name' => 'noticias',
'posts_per_page' => -1,
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC'
]);
}
public function getBotonesEnlaces($page_id = null) {
if (is_null($page_id)) {
$page_id = get_the_ID();
// Si estamos en euskera, obtener la página en español
if (pll_current_language() == 'eu') {
$spanish_page_id = pll_get_post($page_id, 'es');
$page_id = $spanish_page_id ?: $page_id;
}
}
$botones = [];
for ($i = 1; $i <= 4; $i++) {
$imagen = get_field('imagen_boton_' . $i, $page_id);
$enlace = get_field('enlace_boton_' . $i, $page_id);
$botones[] = [
'imagen' => $imagen,
'enlace' => $enlace,
];
}
return $botones;
}
public function getLastPostOpinion() {
return Timber::get_posts([
'post_type' => 'opinion',
'posts_per_page' => 1,
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC'
]);
}
public function getLastPostCampana() {
return Timber::get_posts([
'post_type' => 'post',
'category_name' => 'campana',
'posts_per_page' => 1,
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC'
]);
}
public function getLastPostConflicts() {
return Timber::get_posts([
'post_type' => 'post',
'category_name' => 'conflictos laborales',
'posts_per_page' => 1,
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC'
]);
}
/**
* Funciones globales
*/
// Excluir páginas de la búsqueda
public function exclude_pages_from_search($query) {
if (!is_admin() && $query->is_main_query() && $query->is_search()) {
$query->set('meta_query', array(
'relation' => 'OR',
array(
'key' => 'exclude_from_search',
'compare' => 'NOT EXISTS'
),
array(
'key' => 'exclude_from_search',
'value' => '1',
'compare' => '!='
)
));
}
}
// genera embed para videos
public function generar_embed_universal($url) {
if (empty($url)) {
return false;
}
// YouTube
if (strpos($url, 'youtube.com') !== false || strpos($url, 'youtu.be') !== false) {
//error_log('es un vídeo de youtube'); // Debug
preg_match('/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/', $url, $matches);
if (!empty($matches[1])) {
$embed_data = [
'platform' => 'youtube',
'embed_url' => 'https://www.youtube.com/embed/' . $matches[1] . '?rel=0&modestbranding=1',
'thumbnail_url' => 'https://img.youtube.com/vi/' . $matches[1]. '/hqdefault.jpg',
'allow' => 'autoplay; encrypted-media; picture-in-picture'
];
//error_log('Embed URL generada: ' . $embed_data['embed_url']);
return $embed_data;
} else {
error_log('No se pudo extraer ID de YouTube');
}
}
// Vimeo
if (strpos($url, 'vimeo.com') !== false) {
preg_match('/vimeo\.com\/(\d+)/', $url, $matches);
if (!empty($matches[1])) {
return [
'platform' => 'vimeo',
'embed_url' => 'https://player.vimeo.com/video/' . $matches[1] . '?title=0&byline=0&portrait=0',
'allow' => 'autoplay; fullscreen; picture-in-picture'
];
}
}
// Si no se reconoce la plataforma
return [
'platform' => 'generic',
'embed_url' => $url,
'allow' => 'fullscreen'
];
}
// Hacer función disponible en Twig
public function add_videos_embed_to_twig ($twig) {
//error_log('Añadiendo función generar_embed a Twig'); // Debug
$twig->addFunction(new \Twig\TwigFunction('generar_embed', [$this, 'generar_embed_universal']));
return $twig;
}
}