diff --git a/alcastromol-function.php b/alcastromol-function.php
index 7a64633..e5b0eba 100644
--- a/alcastromol-function.php
+++ b/alcastromol-function.php
@@ -178,6 +178,7 @@ register_deactivation_hook(__FILE__, 'alcastromol_cleanup_options');
alcastromol_require('functions/admin/modules-dashboard.php');
alcastromol_require('functions/optimizer/optimizer.php');
+alcastromol_require('functions/animejs/animejs.php');
/*
|--------------------------------------------------------------------------
diff --git a/functions/admin/modules-dashboard.php b/functions/admin/modules-dashboard.php
index 1a9cda8..4cb871c 100644
--- a/functions/admin/modules-dashboard.php
+++ b/functions/admin/modules-dashboard.php
@@ -16,6 +16,7 @@ function alcastromol_default_modules() {
'tailwind' => '1',
'cache' => '1',
'optimizer' => '0',
+ 'animejs' => '0',
];
}
@@ -46,6 +47,7 @@ function alcastromol_module_icon($name) {
'tailwind' => ' ',
'cache' => ' ',
'optimizer' => ' ',
+ 'animejs' => ' ',
];
return isset($icons[$name]) ? $icons[$name] : '';
@@ -85,6 +87,16 @@ function alcastromol_get_module_cards() {
'badge' => '',
'locked' => false,
],
+ 'animejs' => [
+ 'title' => 'Anime.js',
+ 'desc' => 'Carga Anime.js 4 desde el CDN. Cada import (animate, text, utils y el resto) se activa por separado y solo entra al sitio el que esté encendido.',
+ 'settings' => admin_url('admin.php?page=alcastromol-animejs'),
+ 'bg' => '#fff1e8',
+ 'color' => '#ea580c',
+ 'icon' => 'animejs',
+ 'badge' => '',
+ 'locked' => false,
+ ],
];
}
@@ -122,7 +134,7 @@ add_action('wp_ajax_alcastromol_toggle_module', function () {
$module = sanitize_key($_POST['module'] ?? '');
$active = ($_POST['active'] ?? '0') === '1' ? '1' : '0';
- $allowed = ['tailwind', 'cache', 'optimizer'];
+ $allowed = ['tailwind', 'cache', 'optimizer', 'animejs'];
if (!in_array($module, $allowed, true)) {
wp_send_json_error(['message' => 'Esta función todavía no se puede activar.'], 400);
diff --git a/functions/animejs/animejs.php b/functions/animejs/animejs.php
new file mode 100644
index 0000000..c4d5e8a
--- /dev/null
+++ b/functions/animejs/animejs.php
@@ -0,0 +1,428 @@
+ [
+ 'label' => 'animate',
+ 'import' => "import { animate } from 'animejs/animation'",
+ 'path' => 'animation/index.js',
+ 'desc' => 'Animaciones con animate().',
+ ],
+ 'text' => [
+ 'label' => 'text',
+ 'import' => "import { splitText } from 'animejs/text'",
+ 'path' => 'text/index.js',
+ 'desc' => 'Parte títulos y párrafos en líneas, palabras o letras.',
+ ],
+ 'utils' => [
+ 'label' => 'utils',
+ 'import' => "import { stagger, random } from 'animejs/utils'",
+ 'path' => 'utils/index.js',
+ 'desc' => 'stagger, random y utilidades de tiempo y targets.',
+ ],
+ 'timeline' => [
+ 'label' => 'timeline',
+ 'import' => "import { createTimeline } from 'animejs/timeline'",
+ 'path' => 'timeline/index.js',
+ 'desc' => 'Secuencias con createTimeline().',
+ ],
+ 'timer' => [
+ 'label' => 'timer',
+ 'import' => "import { createTimer } from 'animejs/timer'",
+ 'path' => 'timer/index.js',
+ 'desc' => 'Temporizadores con createTimer().',
+ ],
+ 'animatable' => [
+ 'label' => 'animatable',
+ 'import' => "import { createAnimatable } from 'animejs/animatable'",
+ 'path' => 'animatable/index.js',
+ 'desc' => 'Valores animables que se actualizan al vuelo.',
+ ],
+ 'draggable' => [
+ 'label' => 'draggable',
+ 'import' => "import { createDraggable } from 'animejs/draggable'",
+ 'path' => 'draggable/index.js',
+ 'desc' => 'Arrastre con createDraggable().',
+ ],
+ 'layout' => [
+ 'label' => 'layout',
+ 'import' => "import { createLayout } from 'animejs/layout'",
+ 'path' => 'layout/index.js',
+ 'desc' => 'Transiciones de layout con createLayout().',
+ ],
+ 'scope' => [
+ 'label' => 'scope',
+ 'import' => "import { createScope } from 'animejs/scope'",
+ 'path' => 'scope/index.js',
+ 'desc' => 'Agrupa animaciones y las limpia con el scope.',
+ ],
+ 'engine' => [
+ 'label' => 'engine',
+ 'import' => "import { engine } from 'animejs/engine'",
+ 'path' => 'engine/index.js',
+ 'desc' => 'Control del motor: pausa, tiempo y velocidad.',
+ ],
+ 'easings' => [
+ 'label' => 'easings',
+ 'import' => "import * as easings from 'animejs/easings'",
+ 'path' => 'easings/index.js',
+ 'desc' => 'Curvas, spring y cubic-bezier.',
+ ],
+ 'svg' => [
+ 'label' => 'svg',
+ 'import' => "import * as svg from 'animejs/svg'",
+ 'path' => 'svg/index.js',
+ 'desc' => 'Motion path, morph y drawable.',
+ ],
+ 'waapi' => [
+ 'label' => 'waapi',
+ 'import' => "import { waapi } from 'animejs/waapi'",
+ 'path' => 'waapi/index.js',
+ 'desc' => 'animate() ligero sobre la Web Animations API.',
+ ],
+ 'events' => [
+ 'label' => 'events',
+ 'import' => "import * as events from 'animejs/events'",
+ 'path' => 'events/index.js',
+ 'desc' => 'Scroll y otros observadores de eventos.',
+ ],
+ ];
+
+}
+
+function alcastromol_animejs_default_imports() {
+
+ $defaults = [];
+
+ foreach (alcastromol_animejs_catalog() as $id => $item) {
+ $defaults[$id] = $id === 'animation' ? '1' : '0';
+ }
+
+ return $defaults;
+
+}
+
+function alcastromol_animejs_get_imports() {
+
+ $saved = get_option(ALCASTROMOL_ANIMEJS_OPTION, null);
+ $defaults = alcastromol_animejs_default_imports();
+
+ if (!is_array($saved)) {
+ return $defaults;
+ }
+
+ $imports = $defaults;
+
+ foreach ($defaults as $id => $value) {
+ if (array_key_exists($id, $saved)) {
+ $imports[$id] = $saved[$id] === '1' ? '1' : '0';
+ }
+ }
+
+ return $imports;
+
+}
+
+function alcastromol_animejs_is_import_active($id) {
+
+ $imports = alcastromol_animejs_get_imports();
+
+ return isset($imports[$id]) && $imports[$id] === '1';
+
+}
+
+function alcastromol_animejs_module_url($path) {
+
+ return 'https://cdn.jsdelivr.net/npm/animejs@' . ALCASTROMOL_ANIMEJS_VERSION . '/dist/modules/' . ltrim($path, '/');
+
+}
+
+function alcastromol_animejs_should_load() {
+
+ if (is_admin() || wp_doing_ajax() || wp_doing_cron()) {
+ return false;
+ }
+
+ if (defined('REST_REQUEST') && REST_REQUEST) {
+ return false;
+ }
+
+ if (is_feed() || is_embed() || is_customize_preview()) {
+ return false;
+ }
+
+ if (function_exists('alcastromol_is_module_active') && !alcastromol_is_module_active('animejs')) {
+ return false;
+ }
+
+ if (function_exists('alcastromol_is_tailwind_builder_context') && alcastromol_is_tailwind_builder_context()) {
+ return false;
+ }
+
+ return true;
+
+}
+
+function alcastromol_animejs_enabled_ids() {
+
+ $enabled = [];
+
+ foreach (alcastromol_animejs_get_imports() as $id => $active) {
+ if ($active === '1' && isset(alcastromol_animejs_catalog()[$id])) {
+ $enabled[] = $id;
+ }
+ }
+
+ return $enabled;
+
+}
+
+function alcastromol_animejs_print() {
+
+ if (!alcastromol_animejs_should_load()) {
+ return;
+ }
+
+ $catalog = alcastromol_animejs_catalog();
+ $enabled = alcastromol_animejs_enabled_ids();
+
+ if (!$enabled) {
+ return;
+ }
+
+ $imports = [];
+ $pairs = [];
+
+ foreach ($enabled as $id) {
+ $alias = 'mod_' . $id;
+ $url = alcastromol_animejs_module_url($catalog[$id]['path']);
+ $imports[] = 'import * as ' . $alias . " from '" . esc_url($url) . "';";
+ $pairs[] = $id . ': ' . $alias;
+ }
+
+ echo "\n";
+
+}
+
+add_action('wp_head', 'alcastromol_animejs_print', 20);
+
+add_action('admin_menu', function () {
+
+ add_submenu_page(
+ 'alcastromol-functions',
+ 'Anime.js',
+ 'Anime.js',
+ 'manage_options',
+ 'alcastromol-animejs',
+ 'alcastromol_animejs_admin_page'
+ );
+
+}, 22);
+
+add_action('admin_post_alcastromol_animejs_save', function () {
+
+ if (!current_user_can('manage_options')) {
+ wp_die('No tienes permisos.');
+ }
+
+ check_admin_referer('alcastromol_animejs_save');
+
+ $posted = isset($_POST['imports']) && is_array($_POST['imports']) ? wp_unslash($_POST['imports']) : [];
+ $imports = alcastromol_animejs_default_imports();
+
+ foreach ($imports as $id => $value) {
+ $imports[$id] = !empty($posted[$id]) ? '1' : '0';
+ }
+
+ update_option(ALCASTROMOL_ANIMEJS_OPTION, $imports);
+
+ wp_safe_redirect(admin_url('admin.php?page=alcastromol-animejs&updated=1'));
+ exit;
+
+});
+
+function alcastromol_animejs_admin_page() {
+
+ if (!current_user_can('manage_options')) {
+ return;
+ }
+
+ $catalog = alcastromol_animejs_catalog();
+ $imports = alcastromol_animejs_get_imports();
+ $active = function_exists('alcastromol_is_module_active') && alcastromol_is_module_active('animejs');
+
+ ?>
+
+
Anime.js
+
+ Anime.js entra desde jsDelivr.
+ Enciende solo los imports que el sitio va a usar. Quedan en window.animejs cuando dispara animejs:ready.
+
+
+
+
+
Anime.js está apagado. Actívalo en Centro de funciones para cargarlo en el sitio.
+
+
+
+
+
+
Imports de Anime.js guardados.
+
+
+
+
+
+
+ document.addEventListener('animejs:ready', function () { animejs.animate('.card', { opacity: [0, 1], y: [22, 0] }); });
+
+
+
+
+ 1,
+ 'post_types' => [],
+ 'taxonomies' => [],
+ 'authors' => 0,
+ 'oxygen_templates' => 1,
+ ];
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Obtener opciones guardadas
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_get_cache_options() {
+
+ $saved = get_option(ALCASTROMOL_TAILWIND_CACHE_OPTIONS, []);
+
+ if (!is_array($saved)) {
+ $saved = [];
+ }
+
+ return wp_parse_args($saved, alcastromol_get_default_cache_options());
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Guardar opciones
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_save_cache_options($options) {
+
+ $clean = alcastromol_get_default_cache_options();
+
+ $clean['home'] = !empty($options['home']) ? 1 : 0;
+
+ $clean['post_types'] = [];
+
+ if (!empty($options['post_types']) && is_array($options['post_types'])) {
+ foreach ($options['post_types'] as $post_type) {
+ $clean['post_types'][] = sanitize_key($post_type);
+ }
+ }
+
+ $clean['taxonomies'] = [];
+
+ if (!empty($options['taxonomies']) && is_array($options['taxonomies'])) {
+ foreach ($options['taxonomies'] as $taxonomy) {
+ $clean['taxonomies'][] = sanitize_key($taxonomy);
+ }
+ }
+
+ $clean['authors'] = !empty($options['authors']) ? 1 : 0;
+
+ $clean['oxygen_templates'] = !empty($options['oxygen_templates']) ? 1 : 0;
+
+ update_option(ALCASTROMOL_TAILWIND_CACHE_OPTIONS, $clean);
+
+ return $clean;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Detectar post types cacheables
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_detect_cacheable_post_types() {
+
+ $post_types = get_post_types([
+ 'public' => true,
+ ], 'objects');
+
+ $exclude = [
+ 'attachment',
+ ];
+
+ $items = [];
+
+ foreach ($post_types as $post_type => $object) {
+
+ if (in_array($post_type, $exclude, true)) {
+ continue;
+ }
+
+ $items[$post_type] = [
+ 'name' => $post_type,
+ 'label' => $object->labels->name ?? $post_type,
+ ];
+
+ }
+
+ if (post_type_exists('product') && !isset($items['product'])) {
+ $items['product'] = [
+ 'name' => 'product',
+ 'label' => 'Productos WooCommerce',
+ ];
+ }
+
+ return $items;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Detectar taxonomías cacheables
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_detect_cacheable_taxonomies() {
+
+ $taxonomies = get_taxonomies([
+ 'public' => true,
+ ], 'objects');
+
+ $items = [];
+
+ foreach ($taxonomies as $taxonomy => $object) {
+
+ $items[$taxonomy] = [
+ 'name' => $taxonomy,
+ 'label' => $object->labels->name ?? $taxonomy,
+ ];
+
+ }
+
+ return $items;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Obtener HTML final renderizado
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_fetch_html($url) {
+
+ $response = wp_remote_get($url, [
+ 'timeout' => 20,
+ 'sslverify' => false,
+ 'headers' => [
+ 'User-Agent' => 'Alcastromol Tailwind Cache Generator',
+ ],
+ ]);
+
+ if (is_wp_error($response)) {
+ return false;
+ }
+
+ $code = wp_remote_retrieve_response_code($response);
+
+ if ($code < 200 || $code >= 400) {
+ return false;
+ }
+
+ $html = wp_remote_retrieve_body($response);
+
+ if (!$html) {
+ return false;
+ }
+
+ return $html;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Limpiar HTML
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_clean_html($html) {
+
+ $html = preg_replace('//', '', $html);
+
+ return $html;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Guardar cache
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_save_cache($slug, $html) {
+
+ if (!file_exists(ALCASTROMOL_TAILWIND_CACHE)) {
+ wp_mkdir_p(ALCASTROMOL_TAILWIND_CACHE);
+ }
+
+ $file = ALCASTROMOL_TAILWIND_CACHE . sanitize_file_name($slug) . '.html';
+
+ file_put_contents($file, $html);
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Eliminar archivo individual
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_delete_cache_file($slug) {
+
+ $file = ALCASTROMOL_TAILWIND_CACHE . sanitize_file_name($slug) . '.html';
+
+ if (file_exists($file)) {
+ unlink($file);
+ }
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Eliminar todo el cache
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_delete_all_cache() {
+
+ if (!file_exists(ALCASTROMOL_TAILWIND_CACHE)) {
+ return 0;
+ }
+
+ $files = glob(ALCASTROMOL_TAILWIND_CACHE . '*.html');
+
+ if (!$files) {
+ return 0;
+ }
+
+ $deleted = 0;
+
+ foreach ($files as $file) {
+
+ if (is_file($file)) {
+ unlink($file);
+ $deleted++;
+ }
+
+ }
+
+ return $deleted;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Patrones, conteos y acciones por tipo de contenido
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_get_cache_patterns_by_target($target_type, $target_name = '') {
+
+ $target_type = sanitize_key($target_type);
+ $target_name = sanitize_key($target_name);
+
+ switch ($target_type) {
+
+ case 'home':
+ return ['home.html'];
+
+ case 'post_type':
+ if (!$target_name) return [];
+ return [$target_name . '-*.html'];
+
+ case 'taxonomy':
+ if (!$target_name) return [];
+ return ['taxonomy-' . $target_name . '-*.html'];
+
+ case 'oxygen_templates':
+ return ['oxygen-template-*.html'];
+
+ case 'authors':
+ return ['author-*.html'];
+
+ }
+
+ return [];
+
+}
+
+function alcastromol_get_cache_files_by_target($target_type, $target_name = '') {
+
+ if (!file_exists(ALCASTROMOL_TAILWIND_CACHE)) {
+ return [];
+ }
+
+ $patterns = alcastromol_get_cache_patterns_by_target($target_type, $target_name);
+
+ if (empty($patterns)) {
+ return [];
+ }
+
+ $files = [];
+
+ foreach ($patterns as $pattern) {
+
+ $found = glob(ALCASTROMOL_TAILWIND_CACHE . $pattern);
+
+ if (!empty($found)) {
+ $files = array_merge($files, $found);
+ }
+
+ }
+
+ $files = array_filter(array_unique($files), 'is_file');
+
+ return array_values($files);
+
+}
+
+function alcastromol_count_cache_files_by_target($target_type, $target_name = '') {
+
+ return count(alcastromol_get_cache_files_by_target($target_type, $target_name));
+
+}
+
+function alcastromol_delete_cache_by_target($target_type, $target_name = '') {
+
+ $files = alcastromol_get_cache_files_by_target($target_type, $target_name);
+
+ if (empty($files)) {
+ return 0;
+ }
+
+ $deleted = 0;
+
+ foreach ($files as $file) {
+
+ if (is_file($file) && unlink($file)) {
+ $deleted++;
+ }
+
+ }
+
+ return $deleted;
+
+}
+
+function alcastromol_get_urls_by_cache_target($target_type, $target_name = '') {
+
+ $target_type = sanitize_key($target_type);
+ $target_name = sanitize_key($target_name);
+
+ $items = [];
+
+ if ($target_type === 'home') {
+
+ $items[] = [
+ 'url' => home_url('/'),
+ 'slug' => 'home',
+ 'type' => 'home',
+ ];
+
+ return $items;
+
+ }
+
+ if ($target_type === 'post_type') {
+
+ if (!$target_name || !post_type_exists($target_name)) {
+ return [];
+ }
+
+ $post_ids = get_posts([
+ 'post_type' => $target_name,
+ 'post_status' => 'publish',
+ 'posts_per_page' => -1,
+ 'fields' => 'ids',
+ 'no_found_rows' => true,
+ 'ignore_sticky_posts' => true,
+ 'suppress_filters' => false,
+ 'update_post_meta_cache' => false,
+ 'update_post_term_cache' => false,
+ ]);
+
+ foreach ($post_ids as $post_id) {
+
+ $post = get_post($post_id);
+
+ if (!$post) continue;
+
+ $permalink = get_permalink($post_id);
+
+ if (!$permalink) continue;
+
+ $items[] = [
+ 'url' => $permalink,
+ 'slug' => $post->post_type . '-' . $post->ID . '-' . $post->post_name,
+ 'type' => $post->post_type,
+ ];
+
+ }
+
+ return $items;
+
+ }
+
+ if ($target_type === 'taxonomy') {
+
+ if (!$target_name || !taxonomy_exists($target_name)) {
+ return [];
+ }
+
+ $terms = get_terms([
+ 'taxonomy' => $target_name,
+ 'hide_empty' => false,
+ ]);
+
+ if (is_wp_error($terms) || empty($terms)) {
+ return [];
+ }
+
+ foreach ($terms as $term) {
+
+ $term_link = get_term_link($term);
+
+ if (is_wp_error($term_link)) {
+ continue;
+ }
+
+ $items[] = [
+ 'url' => $term_link,
+ 'slug' => 'taxonomy-' . $target_name . '-' . $term->term_id . '-' . $term->slug,
+ 'type' => 'taxonomy_' . $target_name,
+ ];
+
+ }
+
+ return $items;
+
+ }
+
+ if ($target_type === 'authors') {
+
+ $authors = get_users([
+ 'who' => 'authors',
+ ]);
+
+ foreach ($authors as $author) {
+
+ $items[] = [
+ 'url' => get_author_posts_url($author->ID),
+ 'slug' => 'author-' . $author->ID . '-' . $author->user_nicename,
+ 'type' => 'author',
+ ];
+
+ }
+
+ return $items;
+
+ }
+
+ return $items;
+
+}
+
+function alcastromol_generate_cache_by_target($target_type, $target_name = '') {
+
+ $target_type = sanitize_key($target_type);
+ $target_name = sanitize_key($target_name);
+
+ $generated = 0;
+ $failed = 0;
+ $failed_urls = [];
+ $total = 0;
+
+ if ($target_type === 'oxygen_templates') {
+
+ $oxygen_items = alcastromol_get_oxygen_templates_cache_items();
+ $total = count($oxygen_items);
+
+ foreach ($oxygen_items as $item) {
+
+ if (empty($item['slug']) || empty($item['html'])) {
+ $failed++;
+ continue;
+ }
+
+ $html = alcastromol_clean_html($item['html']);
+
+ alcastromol_save_cache($item['slug'], $html);
+
+ $generated++;
+
+ }
+
+ return [
+ 'total' => $total,
+ 'generated' => $generated,
+ 'failed' => $failed,
+ 'failed_urls' => $failed_urls,
+ 'count' => alcastromol_count_cache_files_by_target($target_type, $target_name),
+ ];
+
+ }
+
+ $items = alcastromol_get_urls_by_cache_target($target_type, $target_name);
+ $total = count($items);
+
+ foreach ($items as $item) {
+
+ if (empty($item['url']) || empty($item['slug'])) {
+ $failed++;
+ continue;
+ }
+
+ $result = alcastromol_cache_url($item['url'], $item['slug']);
+
+ if ($result) {
+ $generated++;
+ } else {
+ $failed++;
+ $failed_urls[] = $item['url'];
+ }
+
+ }
+
+ return [
+ 'total' => $total,
+ 'generated' => $generated,
+ 'failed' => $failed,
+ 'failed_urls' => $failed_urls,
+ 'count' => alcastromol_count_cache_files_by_target($target_type, $target_name),
+ ];
+
+}
+
+function alcastromol_render_cache_action_row($args) {
+
+ $target_type = sanitize_key($args['target_type'] ?? '');
+ $target_name = sanitize_key($args['target_name'] ?? '');
+ $label = $args['label'] ?? '';
+ $code = $args['code'] ?? '';
+ $input_name = $args['input_name'] ?? '';
+ $input_value = $args['input_value'] ?? '';
+ $checked = !empty($args['checked']);
+
+ $count = alcastromol_count_cache_files_by_target($target_type, $target_name);
+
+ ?>
+
+
+
+
+ >
+
+
+
+
+
+
+
+
+
+
+ archivos
+
+
+
+ Generar
+
+
+
+ Borrar
+
+
+ post_type . '-' . $post->ID . '-' . $post->post_name;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Cache individual al guardar Gutenberg / post / page / CPT / product
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_cache_post($post_id) {
+
+ if (wp_is_post_revision($post_id)) return;
+
+ if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
+
+ $post = get_post($post_id);
+
+ if (!$post) return;
+
+ if ($post->post_status !== 'publish') return;
+
+ /*
+ | Si es template Oxygen, lo cacheamos con la función especial.
+ */
+
+ if ($post->post_type === 'ct_template') {
+ alcastromol_cache_oxygen_template($post_id);
+ return;
+ }
+
+ $options = alcastromol_get_cache_options();
+
+ if (empty($options['post_types']) || !in_array($post->post_type, $options['post_types'], true)) {
+ return;
+ }
+
+ $url = get_permalink($post_id);
+
+ if (!$url) return;
+
+ $slug = alcastromol_get_post_cache_slug($post_id);
+
+ if (!$slug) return;
+
+ alcastromol_cache_url($url, $slug);
+
+}
+
+add_action('save_post', 'alcastromol_cache_post', 30);
+add_action('save_post_product', 'alcastromol_cache_post', 30);
+add_action('save_post_ct_template', 'alcastromol_cache_post', 30);
+
+
+/*
+|--------------------------------------------------------------------------
+| Obtener HTML/metas de un template Oxygen
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_get_oxygen_template_html($template_id) {
+
+ $post = get_post($template_id);
+
+ if (!$post || $post->post_type !== 'ct_template') {
+ return false;
+ }
+
+ $html_parts = [];
+
+ if (!empty($post->post_content)) {
+ $html_parts[] = $post->post_content;
+ }
+
+ $possible_meta_keys = [
+ 'ct_builder_shortcodes',
+ 'ct_builder_json',
+ 'ct_template_type',
+ 'ct_template_order',
+ 'ct_use_template',
+ 'ct_parent_template',
+ 'ct_inner_content',
+ ];
+
+ foreach ($possible_meta_keys as $meta_key) {
+
+ $meta_value = get_post_meta($template_id, $meta_key, true);
+
+ if (!empty($meta_value)) {
+
+ if (is_array($meta_value) || is_object($meta_value)) {
+ $meta_value = wp_json_encode($meta_value);
+ }
+
+ if (is_string($meta_value)) {
+ $html_parts[] = $meta_value;
+ }
+
+ }
+
+ }
+
+ /*
+ | Extra: tomar todos los metas del template.
+ | Oxygen puede guardar clases y estructura en distintos campos.
+ */
+
+ $all_meta = get_post_meta($template_id);
+
+ if (!empty($all_meta) && is_array($all_meta)) {
+
+ foreach ($all_meta as $meta_key => $meta_values) {
+
+ if (empty($meta_values)) {
+ continue;
+ }
+
+ foreach ($meta_values as $meta_value) {
+
+ if (empty($meta_value)) {
+ continue;
+ }
+
+ if (is_array($meta_value) || is_object($meta_value)) {
+ $meta_value = wp_json_encode($meta_value);
+ }
+
+ if (is_string($meta_value)) {
+ $html_parts[] = $meta_value;
+ }
+
+ }
+
+ }
+
+ }
+
+ $html = implode("\n", array_filter($html_parts));
+
+ if (empty($html)) {
+ return false;
+ }
+
+ return $html;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Cache individual de template Oxygen
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_cache_oxygen_template($template_id) {
+
+ $options = alcastromol_get_cache_options();
+
+ if (empty($options['oxygen_templates'])) {
+ return false;
+ }
+
+ $post = get_post($template_id);
+
+ if (!$post || $post->post_type !== 'ct_template') {
+ return false;
+ }
+
+ if (!in_array($post->post_status, ['publish', 'draft'], true)) {
+ return false;
+ }
+
+ $html = alcastromol_get_oxygen_template_html($template_id);
+
+ if (!$html) {
+ return false;
+ }
+
+ $slug = 'oxygen-template-' . $template_id . '-' . $post->post_name;
+
+ $html = alcastromol_clean_html($html);
+
+ alcastromol_save_cache($slug, $html);
+
+ return true;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Obtener templates Oxygen para cache masivo
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_get_oxygen_templates_cache_items() {
+
+ $items = [];
+
+ if (!post_type_exists('ct_template')) {
+ return $items;
+ }
+
+ $template_ids = get_posts([
+ 'post_type' => 'ct_template',
+ 'post_status' => ['publish', 'draft'],
+ 'posts_per_page' => -1,
+ 'fields' => 'ids',
+ 'no_found_rows' => true,
+ 'ignore_sticky_posts' => true,
+ 'suppress_filters' => false,
+ 'update_post_meta_cache' => true,
+ 'update_post_term_cache' => false,
+ ]);
+
+ foreach ($template_ids as $template_id) {
+
+ $post = get_post($template_id);
+
+ if (!$post) {
+ continue;
+ }
+
+ $html = alcastromol_get_oxygen_template_html($template_id);
+
+ if (!$html) {
+ continue;
+ }
+
+ $items[] = [
+ 'slug' => 'oxygen-template-' . $template_id . '-' . $post->post_name,
+ 'html' => $html,
+ ];
+
+ }
+
+ return $items;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Obtener todas las URLs públicas seleccionadas
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_get_all_urls() {
+
+ $options = alcastromol_get_cache_options();
+
+ $urls = [];
+
+ /*
+ |--------------------------------------------------------------------------
+ | Home
+ |--------------------------------------------------------------------------
+ */
+
+ if (!empty($options['home'])) {
+
+ $urls[] = [
+ 'url' => home_url('/'),
+ 'slug' => 'home',
+ 'type' => 'home',
+ ];
+
+ }
+
+
+ /*
+ |--------------------------------------------------------------------------
+ | Post types seleccionados
+ |--------------------------------------------------------------------------
+ */
+
+ $selected_post_types = [];
+
+ if (!empty($options['post_types']) && is_array($options['post_types'])) {
+ $selected_post_types = $options['post_types'];
+ }
+
+ $selected_post_types = array_filter($selected_post_types, function ($post_type) {
+ return post_type_exists($post_type);
+ });
+
+ if (!empty($selected_post_types)) {
+
+ $post_ids = get_posts([
+ 'post_type' => $selected_post_types,
+ 'post_status' => 'publish',
+ 'posts_per_page' => -1,
+ 'fields' => 'ids',
+ 'no_found_rows' => true,
+ 'ignore_sticky_posts' => true,
+ 'suppress_filters' => false,
+ 'update_post_meta_cache' => false,
+ 'update_post_term_cache' => false,
+ ]);
+
+ foreach ($post_ids as $post_id) {
+
+ $post = get_post($post_id);
+
+ if (!$post) continue;
+
+ $permalink = get_permalink($post_id);
+
+ if (!$permalink) continue;
+
+ $urls[] = [
+ 'url' => $permalink,
+ 'slug' => $post->post_type . '-' . $post->ID . '-' . $post->post_name,
+ 'type' => $post->post_type,
+ ];
+
+ }
+
+ }
+
+
+ /*
+ |--------------------------------------------------------------------------
+ | Taxonomías seleccionadas
+ |--------------------------------------------------------------------------
+ */
+
+ $selected_taxonomies = [];
+
+ if (!empty($options['taxonomies']) && is_array($options['taxonomies'])) {
+ $selected_taxonomies = $options['taxonomies'];
+ }
+
+ $selected_taxonomies = array_filter($selected_taxonomies, function ($taxonomy) {
+ return taxonomy_exists($taxonomy);
+ });
+
+ if (!empty($selected_taxonomies)) {
+
+ foreach ($selected_taxonomies as $tax) {
+
+ $terms = get_terms([
+ 'taxonomy' => $tax,
+ 'hide_empty' => false,
+ ]);
+
+ if (is_wp_error($terms) || empty($terms)) {
+ continue;
+ }
+
+ foreach ($terms as $term) {
+
+ $term_link = get_term_link($term);
+
+ if (is_wp_error($term_link)) {
+ continue;
+ }
+
+ $urls[] = [
+ 'url' => $term_link,
+ 'slug' => 'taxonomy-' . $tax . '-' . $term->term_id . '-' . $term->slug,
+ 'type' => 'taxonomy_' . $tax,
+ ];
+
+ }
+
+ }
+
+ }
+
+
+ /*
+ |--------------------------------------------------------------------------
+ | Autores
+ |--------------------------------------------------------------------------
+ */
+
+ if (!empty($options['authors'])) {
+
+ $authors = get_users([
+ 'who' => 'authors',
+ ]);
+
+ foreach ($authors as $author) {
+
+ $urls[] = [
+ 'url' => get_author_posts_url($author->ID),
+ 'slug' => 'author-' . $author->ID . '-' . $author->user_nicename,
+ 'type' => 'author',
+ ];
+
+ }
+
+ }
+
+
+ /*
+ |--------------------------------------------------------------------------
+ | Eliminar URLs duplicadas
+ |--------------------------------------------------------------------------
+ */
+
+ $unique_urls = [];
+
+ foreach ($urls as $item) {
+
+ if (empty($item['url']) || empty($item['slug'])) {
+ continue;
+ }
+
+ $unique_urls[$item['url']] = $item;
+
+ }
+
+ return array_values($unique_urls);
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Generar cache completa
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_generate_full_cache() {
+
+ $options = alcastromol_get_cache_options();
+
+ $urls = alcastromol_get_all_urls();
+
+ $generated = 0;
+ $failed = 0;
+ $products = 0;
+ $oxygen_templates = 0;
+ $failed_urls = [];
+
+ /*
+ |--------------------------------------------------------------------------
+ | Cache de URLs públicas
+ |--------------------------------------------------------------------------
+ */
+
+ foreach ($urls as $item) {
+
+ if (!empty($item['type']) && $item['type'] === 'product') {
+ $products++;
+ }
+
+ $result = alcastromol_cache_url($item['url'], $item['slug']);
+
+ if ($result) {
+ $generated++;
+ } else {
+ $failed++;
+ $failed_urls[] = $item['url'];
+ }
+
+ }
+
+
+ /*
+ |--------------------------------------------------------------------------
+ | Cache de templates Oxygen
+ |--------------------------------------------------------------------------
+ */
+
+ if (!empty($options['oxygen_templates'])) {
+
+ $oxygen_items = alcastromol_get_oxygen_templates_cache_items();
+
+ foreach ($oxygen_items as $item) {
+
+ if (empty($item['slug']) || empty($item['html'])) {
+ continue;
+ }
+
+ $html = alcastromol_clean_html($item['html']);
+
+ alcastromol_save_cache($item['slug'], $html);
+
+ $oxygen_templates++;
+ $generated++;
+
+ }
+
+ }
+
+
+ return [
+ 'total' => count($urls) + $oxygen_templates,
+ 'products' => $products,
+ 'oxygen_templates' => $oxygen_templates,
+ 'generated' => $generated,
+ 'failed' => $failed,
+ 'failed_urls' => $failed_urls,
+ ];
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| AJAX guardar opciones
+|--------------------------------------------------------------------------
+*/
+
+add_action('wp_ajax_alcastromol_save_tailwind_cache_options', function () {
+
+ if (!current_user_can('manage_options')) {
+ wp_send_json_error('No tienes permisos para guardar opciones.');
+ }
+
+ check_ajax_referer('alcastromol_tailwind_cache_nonce', 'nonce');
+
+ $raw_options = $_POST['options'] ?? [];
+
+ if (!is_array($raw_options)) {
+ $raw_options = [];
+ }
+
+ $options = alcastromol_save_cache_options($raw_options);
+
+ wp_send_json_success([
+ 'message' => 'Opciones guardadas',
+ 'options' => $options,
+ ]);
+
+});
+
+
+/*
+|--------------------------------------------------------------------------
+| AJAX generar cache
+|--------------------------------------------------------------------------
+*/
+
+add_action('wp_ajax_alcastromol_generate_tailwind_cache', function () {
+
+ if (!current_user_can('manage_options')) {
+ wp_send_json_error('No tienes permisos para generar el cache.');
+ }
+
+ check_ajax_referer('alcastromol_tailwind_cache_nonce', 'nonce');
+
+ $result = alcastromol_generate_full_cache();
+
+ wp_send_json_success([
+ 'message' => 'Cache generada',
+ 'total' => $result['total'],
+ 'products' => $result['products'],
+ 'oxygen_templates' => $result['oxygen_templates'],
+ 'generated' => $result['generated'],
+ 'failed' => $result['failed'],
+ 'failed_urls' => $result['failed_urls'],
+ ]);
+
+});
+
+
+/*
+|--------------------------------------------------------------------------
+| AJAX eliminar cache
+|--------------------------------------------------------------------------
+*/
+
+add_action('wp_ajax_alcastromol_delete_tailwind_cache', function () {
+
+ if (!current_user_can('manage_options')) {
+ wp_send_json_error('No tienes permisos para eliminar el cache.');
+ }
+
+ check_ajax_referer('alcastromol_tailwind_cache_nonce', 'nonce');
+
+ $deleted = alcastromol_delete_all_cache();
+
+ wp_send_json_success([
+ 'message' => 'Cache eliminado',
+ 'deleted' => $deleted,
+ ]);
+
+});
+
+
+/*
+|--------------------------------------------------------------------------
+| AJAX generar cache por tipo de contenido
+|--------------------------------------------------------------------------
+*/
+
+add_action('wp_ajax_alcastromol_generate_tailwind_cache_target', function () {
+
+ if (!current_user_can('manage_options')) {
+ wp_send_json_error('No tienes permisos para generar este cache.');
+ }
+
+ check_ajax_referer('alcastromol_tailwind_cache_nonce', 'nonce');
+
+ $target_type = sanitize_key($_POST['target_type'] ?? '');
+ $target_name = sanitize_key($_POST['target_name'] ?? '');
+
+ $allowed = ['home', 'post_type', 'taxonomy', 'oxygen_templates', 'authors'];
+
+ if (!in_array($target_type, $allowed, true)) {
+ wp_send_json_error('Tipo de cache inválido.');
+ }
+
+ $result = alcastromol_generate_cache_by_target($target_type, $target_name);
+
+ wp_send_json_success([
+ 'message' => 'Cache generado',
+ 'target_type' => $target_type,
+ 'target_name' => $target_name,
+ 'total' => $result['total'],
+ 'generated' => $result['generated'],
+ 'failed' => $result['failed'],
+ 'failed_urls' => $result['failed_urls'],
+ 'count' => $result['count'],
+ ]);
+
+});
+
+
+/*
+|--------------------------------------------------------------------------
+| POST administrativo para generar cache por tipo de contenido
+|--------------------------------------------------------------------------
+*/
+add_action('admin_post_alcastromol_generate_tailwind_cache_target_post', function () {
+ if (!current_user_can('manage_options')) {
+ wp_die('No tienes permisos para generar este cache.');
+ }
+ check_admin_referer('alcastromol_tailwind_cache_nonce', 'nonce');
+ $target_type = sanitize_key($_POST['target_type'] ?? '');
+ $target_name = sanitize_key($_POST['target_name'] ?? '');
+ $allowed = ['home', 'post_type', 'taxonomy', 'oxygen_templates', 'authors'];
+ if (!in_array($target_type, $allowed, true)) {
+ wp_die('Tipo de cache inválido.');
+ }
+ if (function_exists('set_time_limit')) {
+ @set_time_limit(0);
+ }
+ ignore_user_abort(true);
+ $result = alcastromol_generate_cache_by_target($target_type, $target_name);
+ $redirect = add_query_arg([
+ 'page' => 'tailwind-cache',
+ 'cache_target_result' => 'generated',
+ 'cache_target_type' => $target_type,
+ 'cache_target_name' => $target_name,
+ 'cache_target_total' => (int) $result['total'],
+ 'cache_target_created' => (int) $result['generated'],
+ 'cache_target_failed' => (int) $result['failed'],
+ 'cache_target_count' => (int) $result['count'],
+ ], admin_url('tools.php'));
+ wp_safe_redirect($redirect);
+ exit;
+});
+
+
+/*
+|--------------------------------------------------------------------------
+| AJAX eliminar cache por tipo de contenido
+|--------------------------------------------------------------------------
+*/
+
+add_action('wp_ajax_alcastromol_delete_tailwind_cache_target', function () {
+
+ if (!current_user_can('manage_options')) {
+ wp_send_json_error('No tienes permisos para eliminar este cache.');
+ }
+
+ check_ajax_referer('alcastromol_tailwind_cache_nonce', 'nonce');
+
+ $target_type = sanitize_key($_POST['target_type'] ?? '');
+ $target_name = sanitize_key($_POST['target_name'] ?? '');
+
+ $allowed = ['home', 'post_type', 'taxonomy', 'oxygen_templates', 'authors'];
+
+ if (!in_array($target_type, $allowed, true)) {
+ wp_send_json_error('Tipo de cache inválido.');
+ }
+
+ $deleted = alcastromol_delete_cache_by_target($target_type, $target_name);
+
+ wp_send_json_success([
+ 'message' => 'Cache eliminado',
+ 'target_type' => $target_type,
+ 'target_name' => $target_name,
+ 'deleted' => $deleted,
+ 'count' => alcastromol_count_cache_files_by_target($target_type, $target_name),
+ ]);
+
+});
+
+
+/*
+|--------------------------------------------------------------------------
+| Página herramientas
+|--------------------------------------------------------------------------
+*/
+
+add_action('admin_menu', function () {
+
+ add_management_page(
+ 'Tailwind Cache',
+ 'Tailwind Cache',
+ 'manage_options',
+ 'tailwind-cache',
+ 'alcastromol_tailwind_tools_page'
+ );
+
+});
+
+
+function alcastromol_tailwind_tools_page() {
+
+ $options = alcastromol_get_cache_options();
+
+ $post_types = alcastromol_detect_cacheable_post_types();
+
+ $taxonomies = alcastromol_detect_cacheable_taxonomies();
+
+ $nonce = wp_create_nonce('alcastromol_tailwind_cache_nonce');
+
+?>
+
+
+
+
Generar Cache Tailwind
+
+
+ Selecciona qué contenido quieres cachear para que Tailwind detecte clases de Gutenberg,
+ WooCommerce, CPTs, taxonomías y templates de Oxygen.
+
+
+
+
+
Contenido cacheable detectado
+
+
+
+
+
+
+ Cache generado correctamente.
+ Tipo:
+ Items encontrados: ·
+ Generados: ·
+ Fallidos: ·
+ Archivos actuales:
+
+
+
+
+
+
+
+
+ Guardar selección
+
+
+
+ Generar cache seleccionado
+
+
+
+ Eliminar todo el cache
+
+
+
+
+
+
+
+
+
+ 1,
+ 'post_types' => [],
+ 'taxonomies' => [],
+ 'authors' => 0,
+ 'oxygen_templates' => 1,
+ ];
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Obtener opciones guardadas
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_get_cache_options() {
+
+ $saved = get_option(ALCASTROMOL_TAILWIND_CACHE_OPTIONS, []);
+
+ if (!is_array($saved)) {
+ $saved = [];
+ }
+
+ return wp_parse_args($saved, alcastromol_get_default_cache_options());
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Guardar opciones
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_save_cache_options($options) {
+
+ $clean = alcastromol_get_default_cache_options();
+
+ $clean['home'] = !empty($options['home']) ? 1 : 0;
+
+ $clean['post_types'] = [];
+
+ if (!empty($options['post_types']) && is_array($options['post_types'])) {
+ foreach ($options['post_types'] as $post_type) {
+ $clean['post_types'][] = sanitize_key($post_type);
+ }
+ }
+
+ $clean['taxonomies'] = [];
+
+ if (!empty($options['taxonomies']) && is_array($options['taxonomies'])) {
+ foreach ($options['taxonomies'] as $taxonomy) {
+ $clean['taxonomies'][] = sanitize_key($taxonomy);
+ }
+ }
+
+ $clean['authors'] = !empty($options['authors']) ? 1 : 0;
+
+ $clean['oxygen_templates'] = !empty($options['oxygen_templates']) ? 1 : 0;
+
+ update_option(ALCASTROMOL_TAILWIND_CACHE_OPTIONS, $clean);
+
+ return $clean;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Detectar post types cacheables
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_detect_cacheable_post_types() {
+
+ $post_types = get_post_types([
+ 'public' => true,
+ ], 'objects');
+
+ $exclude = [
+ 'attachment',
+ ];
+
+ $items = [];
+
+ foreach ($post_types as $post_type => $object) {
+
+ if (in_array($post_type, $exclude, true)) {
+ continue;
+ }
+
+ $items[$post_type] = [
+ 'name' => $post_type,
+ 'label' => $object->labels->name ?? $post_type,
+ ];
+
+ }
+
+ if (post_type_exists('product') && !isset($items['product'])) {
+ $items['product'] = [
+ 'name' => 'product',
+ 'label' => 'Productos WooCommerce',
+ ];
+ }
+
+ return $items;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Detectar taxonomías cacheables
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_detect_cacheable_taxonomies() {
+
+ $taxonomies = get_taxonomies([
+ 'public' => true,
+ ], 'objects');
+
+ $items = [];
+
+ foreach ($taxonomies as $taxonomy => $object) {
+
+ $items[$taxonomy] = [
+ 'name' => $taxonomy,
+ 'label' => $object->labels->name ?? $taxonomy,
+ ];
+
+ }
+
+ return $items;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Obtener HTML final renderizado
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_fetch_html($url) {
+
+ $response = wp_remote_get($url, [
+ 'timeout' => 20,
+ 'sslverify' => false,
+ 'headers' => [
+ 'User-Agent' => 'Alcastromol Tailwind Cache Generator',
+ ],
+ ]);
+
+ if (is_wp_error($response)) {
+ return false;
+ }
+
+ $code = wp_remote_retrieve_response_code($response);
+
+ if ($code < 200 || $code >= 400) {
+ return false;
+ }
+
+ $html = wp_remote_retrieve_body($response);
+
+ if (!$html) {
+ return false;
+ }
+
+ return $html;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Limpiar HTML
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_clean_html($html) {
+
+ $html = preg_replace('//', '', $html);
+
+ return $html;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Guardar cache
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_save_cache($slug, $html) {
+
+ if (!file_exists(ALCASTROMOL_TAILWIND_CACHE)) {
+ wp_mkdir_p(ALCASTROMOL_TAILWIND_CACHE);
+ }
+
+ $file = ALCASTROMOL_TAILWIND_CACHE . sanitize_file_name($slug) . '.html';
+
+ file_put_contents($file, $html);
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Eliminar archivo individual
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_delete_cache_file($slug) {
+
+ $file = ALCASTROMOL_TAILWIND_CACHE . sanitize_file_name($slug) . '.html';
+
+ if (file_exists($file)) {
+ unlink($file);
+ }
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Eliminar todo el cache
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_delete_all_cache() {
+
+ if (!file_exists(ALCASTROMOL_TAILWIND_CACHE)) {
+ return 0;
+ }
+
+ $files = glob(ALCASTROMOL_TAILWIND_CACHE . '*.html');
+
+ if (!$files) {
+ return 0;
+ }
+
+ $deleted = 0;
+
+ foreach ($files as $file) {
+
+ if (is_file($file)) {
+ unlink($file);
+ $deleted++;
+ }
+
+ }
+
+ return $deleted;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Patrones, conteos y acciones por tipo de contenido
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_get_cache_patterns_by_target($target_type, $target_name = '') {
+
+ $target_type = sanitize_key($target_type);
+ $target_name = sanitize_key($target_name);
+
+ switch ($target_type) {
+
+ case 'home':
+ return ['home.html'];
+
+ case 'post_type':
+ if (!$target_name) return [];
+ return [$target_name . '-*.html'];
+
+ case 'taxonomy':
+ if (!$target_name) return [];
+ return ['taxonomy-' . $target_name . '-*.html'];
+
+ case 'oxygen_templates':
+ return ['oxygen-template-*.html'];
+
+ case 'authors':
+ return ['author-*.html'];
+
+ }
+
+ return [];
+
+}
+
+function alcastromol_get_cache_files_by_target($target_type, $target_name = '') {
+
+ if (!file_exists(ALCASTROMOL_TAILWIND_CACHE)) {
+ return [];
+ }
+
+ $patterns = alcastromol_get_cache_patterns_by_target($target_type, $target_name);
+
+ if (empty($patterns)) {
+ return [];
+ }
+
+ $files = [];
+
+ foreach ($patterns as $pattern) {
+
+ $found = glob(ALCASTROMOL_TAILWIND_CACHE . $pattern);
+
+ if (!empty($found)) {
+ $files = array_merge($files, $found);
+ }
+
+ }
+
+ $files = array_filter(array_unique($files), 'is_file');
+
+ return array_values($files);
+
+}
+
+function alcastromol_count_cache_files_by_target($target_type, $target_name = '') {
+
+ return count(alcastromol_get_cache_files_by_target($target_type, $target_name));
+
+}
+
+function alcastromol_delete_cache_by_target($target_type, $target_name = '') {
+
+ $files = alcastromol_get_cache_files_by_target($target_type, $target_name);
+
+ if (empty($files)) {
+ return 0;
+ }
+
+ $deleted = 0;
+
+ foreach ($files as $file) {
+
+ if (is_file($file) && unlink($file)) {
+ $deleted++;
+ }
+
+ }
+
+ return $deleted;
+
+}
+
+function alcastromol_get_urls_by_cache_target($target_type, $target_name = '') {
+
+ $target_type = sanitize_key($target_type);
+ $target_name = sanitize_key($target_name);
+
+ $items = [];
+
+ if ($target_type === 'home') {
+
+ $items[] = [
+ 'url' => home_url('/'),
+ 'slug' => 'home',
+ 'type' => 'home',
+ ];
+
+ return $items;
+
+ }
+
+ if ($target_type === 'post_type') {
+
+ if (!$target_name || !post_type_exists($target_name)) {
+ return [];
+ }
+
+ $post_ids = get_posts([
+ 'post_type' => $target_name,
+ 'post_status' => 'publish',
+ 'posts_per_page' => -1,
+ 'fields' => 'ids',
+ 'no_found_rows' => true,
+ 'ignore_sticky_posts' => true,
+ 'suppress_filters' => false,
+ 'update_post_meta_cache' => false,
+ 'update_post_term_cache' => false,
+ ]);
+
+ foreach ($post_ids as $post_id) {
+
+ $post = get_post($post_id);
+
+ if (!$post) continue;
+
+ $permalink = get_permalink($post_id);
+
+ if (!$permalink) continue;
+
+ $items[] = [
+ 'url' => $permalink,
+ 'slug' => $post->post_type . '-' . $post->ID . '-' . $post->post_name,
+ 'type' => $post->post_type,
+ ];
+
+ }
+
+ return $items;
+
+ }
+
+ if ($target_type === 'taxonomy') {
+
+ if (!$target_name || !taxonomy_exists($target_name)) {
+ return [];
+ }
+
+ $terms = get_terms([
+ 'taxonomy' => $target_name,
+ 'hide_empty' => false,
+ ]);
+
+ if (is_wp_error($terms) || empty($terms)) {
+ return [];
+ }
+
+ foreach ($terms as $term) {
+
+ $term_link = get_term_link($term);
+
+ if (is_wp_error($term_link)) {
+ continue;
+ }
+
+ $items[] = [
+ 'url' => $term_link,
+ 'slug' => 'taxonomy-' . $target_name . '-' . $term->term_id . '-' . $term->slug,
+ 'type' => 'taxonomy_' . $target_name,
+ ];
+
+ }
+
+ return $items;
+
+ }
+
+ if ($target_type === 'authors') {
+
+ $authors = get_users([
+ 'who' => 'authors',
+ ]);
+
+ foreach ($authors as $author) {
+
+ $items[] = [
+ 'url' => get_author_posts_url($author->ID),
+ 'slug' => 'author-' . $author->ID . '-' . $author->user_nicename,
+ 'type' => 'author',
+ ];
+
+ }
+
+ return $items;
+
+ }
+
+ return $items;
+
+}
+
+function alcastromol_generate_cache_by_target($target_type, $target_name = '') {
+
+ $target_type = sanitize_key($target_type);
+ $target_name = sanitize_key($target_name);
+
+ $generated = 0;
+ $failed = 0;
+ $failed_urls = [];
+ $total = 0;
+
+ if ($target_type === 'oxygen_templates') {
+
+ $oxygen_items = alcastromol_get_oxygen_templates_cache_items();
+ $total = count($oxygen_items);
+
+ foreach ($oxygen_items as $item) {
+
+ if (empty($item['slug']) || empty($item['html'])) {
+ $failed++;
+ continue;
+ }
+
+ $html = alcastromol_clean_html($item['html']);
+
+ alcastromol_save_cache($item['slug'], $html);
+
+ $generated++;
+
+ }
+
+ return [
+ 'total' => $total,
+ 'generated' => $generated,
+ 'failed' => $failed,
+ 'failed_urls' => $failed_urls,
+ 'count' => alcastromol_count_cache_files_by_target($target_type, $target_name),
+ ];
+
+ }
+
+ $items = alcastromol_get_urls_by_cache_target($target_type, $target_name);
+ $total = count($items);
+
+ foreach ($items as $item) {
+
+ if (empty($item['url']) || empty($item['slug'])) {
+ $failed++;
+ continue;
+ }
+
+ $result = alcastromol_cache_url($item['url'], $item['slug']);
+
+ if ($result) {
+ $generated++;
+ } else {
+ $failed++;
+ $failed_urls[] = $item['url'];
+ }
+
+ }
+
+ return [
+ 'total' => $total,
+ 'generated' => $generated,
+ 'failed' => $failed,
+ 'failed_urls' => $failed_urls,
+ 'count' => alcastromol_count_cache_files_by_target($target_type, $target_name),
+ ];
+
+}
+
+function alcastromol_render_cache_action_row($args) {
+
+ $target_type = sanitize_key($args['target_type'] ?? '');
+ $target_name = sanitize_key($args['target_name'] ?? '');
+ $label = $args['label'] ?? '';
+ $code = $args['code'] ?? '';
+ $input_name = $args['input_name'] ?? '';
+ $input_value = $args['input_value'] ?? '';
+ $checked = !empty($args['checked']);
+
+ $count = alcastromol_count_cache_files_by_target($target_type, $target_name);
+
+ ?>
+
+
+
+
+ >
+
+
+
+
+
+
+
+
+
+
+ archivos
+
+
+
+ Generar
+
+
+
+ Borrar
+
+
+ post_type . '-' . $post->ID . '-' . $post->post_name;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Cache individual al guardar Gutenberg / post / page / CPT / product
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_cache_post($post_id) {
+
+ if (wp_is_post_revision($post_id)) return;
+
+ if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
+
+ $post = get_post($post_id);
+
+ if (!$post) return;
+
+ if ($post->post_status !== 'publish') return;
+
+ /*
+ | Si es template Oxygen, lo cacheamos con la función especial.
+ */
+
+ if ($post->post_type === 'ct_template') {
+ alcastromol_cache_oxygen_template($post_id);
+ return;
+ }
+
+ $options = alcastromol_get_cache_options();
+
+ if (empty($options['post_types']) || !in_array($post->post_type, $options['post_types'], true)) {
+ return;
+ }
+
+ $url = get_permalink($post_id);
+
+ if (!$url) return;
+
+ $slug = alcastromol_get_post_cache_slug($post_id);
+
+ if (!$slug) return;
+
+ alcastromol_cache_url($url, $slug);
+
+}
+
+add_action('save_post', 'alcastromol_cache_post', 30);
+add_action('save_post_product', 'alcastromol_cache_post', 30);
+add_action('save_post_ct_template', 'alcastromol_cache_post', 30);
+
+
+/*
+|--------------------------------------------------------------------------
+| Obtener HTML/metas de un template Oxygen
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_get_oxygen_template_html($template_id) {
+
+ $post = get_post($template_id);
+
+ if (!$post || $post->post_type !== 'ct_template') {
+ return false;
+ }
+
+ $html_parts = [];
+
+ if (!empty($post->post_content)) {
+ $html_parts[] = $post->post_content;
+ }
+
+ $possible_meta_keys = [
+ 'ct_builder_shortcodes',
+ 'ct_builder_json',
+ 'ct_template_type',
+ 'ct_template_order',
+ 'ct_use_template',
+ 'ct_parent_template',
+ 'ct_inner_content',
+ ];
+
+ foreach ($possible_meta_keys as $meta_key) {
+
+ $meta_value = get_post_meta($template_id, $meta_key, true);
+
+ if (!empty($meta_value)) {
+
+ if (is_array($meta_value) || is_object($meta_value)) {
+ $meta_value = wp_json_encode($meta_value);
+ }
+
+ if (is_string($meta_value)) {
+ $html_parts[] = $meta_value;
+ }
+
+ }
+
+ }
+
+ /*
+ | Extra: tomar todos los metas del template.
+ | Oxygen puede guardar clases y estructura en distintos campos.
+ */
+
+ $all_meta = get_post_meta($template_id);
+
+ if (!empty($all_meta) && is_array($all_meta)) {
+
+ foreach ($all_meta as $meta_key => $meta_values) {
+
+ if (empty($meta_values)) {
+ continue;
+ }
+
+ foreach ($meta_values as $meta_value) {
+
+ if (empty($meta_value)) {
+ continue;
+ }
+
+ if (is_array($meta_value) || is_object($meta_value)) {
+ $meta_value = wp_json_encode($meta_value);
+ }
+
+ if (is_string($meta_value)) {
+ $html_parts[] = $meta_value;
+ }
+
+ }
+
+ }
+
+ }
+
+ $html = implode("\n", array_filter($html_parts));
+
+ if (empty($html)) {
+ return false;
+ }
+
+ return $html;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Cache individual de template Oxygen
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_cache_oxygen_template($template_id) {
+
+ $options = alcastromol_get_cache_options();
+
+ if (empty($options['oxygen_templates'])) {
+ return false;
+ }
+
+ $post = get_post($template_id);
+
+ if (!$post || $post->post_type !== 'ct_template') {
+ return false;
+ }
+
+ if (!in_array($post->post_status, ['publish', 'draft'], true)) {
+ return false;
+ }
+
+ $html = alcastromol_get_oxygen_template_html($template_id);
+
+ if (!$html) {
+ return false;
+ }
+
+ $slug = 'oxygen-template-' . $template_id . '-' . $post->post_name;
+
+ $html = alcastromol_clean_html($html);
+
+ alcastromol_save_cache($slug, $html);
+
+ return true;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Obtener templates Oxygen para cache masivo
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_get_oxygen_templates_cache_items() {
+
+ $items = [];
+
+ if (!post_type_exists('ct_template')) {
+ return $items;
+ }
+
+ $template_ids = get_posts([
+ 'post_type' => 'ct_template',
+ 'post_status' => ['publish', 'draft'],
+ 'posts_per_page' => -1,
+ 'fields' => 'ids',
+ 'no_found_rows' => true,
+ 'ignore_sticky_posts' => true,
+ 'suppress_filters' => false,
+ 'update_post_meta_cache' => true,
+ 'update_post_term_cache' => false,
+ ]);
+
+ foreach ($template_ids as $template_id) {
+
+ $post = get_post($template_id);
+
+ if (!$post) {
+ continue;
+ }
+
+ $html = alcastromol_get_oxygen_template_html($template_id);
+
+ if (!$html) {
+ continue;
+ }
+
+ $items[] = [
+ 'slug' => 'oxygen-template-' . $template_id . '-' . $post->post_name,
+ 'html' => $html,
+ ];
+
+ }
+
+ return $items;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Obtener todas las URLs públicas seleccionadas
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_get_all_urls() {
+
+ $options = alcastromol_get_cache_options();
+
+ $urls = [];
+
+ /*
+ |--------------------------------------------------------------------------
+ | Home
+ |--------------------------------------------------------------------------
+ */
+
+ if (!empty($options['home'])) {
+
+ $urls[] = [
+ 'url' => home_url('/'),
+ 'slug' => 'home',
+ 'type' => 'home',
+ ];
+
+ }
+
+
+ /*
+ |--------------------------------------------------------------------------
+ | Post types seleccionados
+ |--------------------------------------------------------------------------
+ */
+
+ $selected_post_types = [];
+
+ if (!empty($options['post_types']) && is_array($options['post_types'])) {
+ $selected_post_types = $options['post_types'];
+ }
+
+ $selected_post_types = array_filter($selected_post_types, function ($post_type) {
+ return post_type_exists($post_type);
+ });
+
+ if (!empty($selected_post_types)) {
+
+ $post_ids = get_posts([
+ 'post_type' => $selected_post_types,
+ 'post_status' => 'publish',
+ 'posts_per_page' => -1,
+ 'fields' => 'ids',
+ 'no_found_rows' => true,
+ 'ignore_sticky_posts' => true,
+ 'suppress_filters' => false,
+ 'update_post_meta_cache' => false,
+ 'update_post_term_cache' => false,
+ ]);
+
+ foreach ($post_ids as $post_id) {
+
+ $post = get_post($post_id);
+
+ if (!$post) continue;
+
+ $permalink = get_permalink($post_id);
+
+ if (!$permalink) continue;
+
+ $urls[] = [
+ 'url' => $permalink,
+ 'slug' => $post->post_type . '-' . $post->ID . '-' . $post->post_name,
+ 'type' => $post->post_type,
+ ];
+
+ }
+
+ }
+
+
+ /*
+ |--------------------------------------------------------------------------
+ | Taxonomías seleccionadas
+ |--------------------------------------------------------------------------
+ */
+
+ $selected_taxonomies = [];
+
+ if (!empty($options['taxonomies']) && is_array($options['taxonomies'])) {
+ $selected_taxonomies = $options['taxonomies'];
+ }
+
+ $selected_taxonomies = array_filter($selected_taxonomies, function ($taxonomy) {
+ return taxonomy_exists($taxonomy);
+ });
+
+ if (!empty($selected_taxonomies)) {
+
+ foreach ($selected_taxonomies as $tax) {
+
+ $terms = get_terms([
+ 'taxonomy' => $tax,
+ 'hide_empty' => false,
+ ]);
+
+ if (is_wp_error($terms) || empty($terms)) {
+ continue;
+ }
+
+ foreach ($terms as $term) {
+
+ $term_link = get_term_link($term);
+
+ if (is_wp_error($term_link)) {
+ continue;
+ }
+
+ $urls[] = [
+ 'url' => $term_link,
+ 'slug' => 'taxonomy-' . $tax . '-' . $term->term_id . '-' . $term->slug,
+ 'type' => 'taxonomy_' . $tax,
+ ];
+
+ }
+
+ }
+
+ }
+
+
+ /*
+ |--------------------------------------------------------------------------
+ | Autores
+ |--------------------------------------------------------------------------
+ */
+
+ if (!empty($options['authors'])) {
+
+ $authors = get_users([
+ 'who' => 'authors',
+ ]);
+
+ foreach ($authors as $author) {
+
+ $urls[] = [
+ 'url' => get_author_posts_url($author->ID),
+ 'slug' => 'author-' . $author->ID . '-' . $author->user_nicename,
+ 'type' => 'author',
+ ];
+
+ }
+
+ }
+
+
+ /*
+ |--------------------------------------------------------------------------
+ | Eliminar URLs duplicadas
+ |--------------------------------------------------------------------------
+ */
+
+ $unique_urls = [];
+
+ foreach ($urls as $item) {
+
+ if (empty($item['url']) || empty($item['slug'])) {
+ continue;
+ }
+
+ $unique_urls[$item['url']] = $item;
+
+ }
+
+ return array_values($unique_urls);
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Generar cache completa
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_generate_full_cache() {
+
+ $options = alcastromol_get_cache_options();
+
+ $urls = alcastromol_get_all_urls();
+
+ $generated = 0;
+ $failed = 0;
+ $products = 0;
+ $oxygen_templates = 0;
+ $failed_urls = [];
+
+ /*
+ |--------------------------------------------------------------------------
+ | Cache de URLs públicas
+ |--------------------------------------------------------------------------
+ */
+
+ foreach ($urls as $item) {
+
+ if (!empty($item['type']) && $item['type'] === 'product') {
+ $products++;
+ }
+
+ $result = alcastromol_cache_url($item['url'], $item['slug']);
+
+ if ($result) {
+ $generated++;
+ } else {
+ $failed++;
+ $failed_urls[] = $item['url'];
+ }
+
+ }
+
+
+ /*
+ |--------------------------------------------------------------------------
+ | Cache de templates Oxygen
+ |--------------------------------------------------------------------------
+ */
+
+ if (!empty($options['oxygen_templates'])) {
+
+ $oxygen_items = alcastromol_get_oxygen_templates_cache_items();
+
+ foreach ($oxygen_items as $item) {
+
+ if (empty($item['slug']) || empty($item['html'])) {
+ continue;
+ }
+
+ $html = alcastromol_clean_html($item['html']);
+
+ alcastromol_save_cache($item['slug'], $html);
+
+ $oxygen_templates++;
+ $generated++;
+
+ }
+
+ }
+
+
+ return [
+ 'total' => count($urls) + $oxygen_templates,
+ 'products' => $products,
+ 'oxygen_templates' => $oxygen_templates,
+ 'generated' => $generated,
+ 'failed' => $failed,
+ 'failed_urls' => $failed_urls,
+ ];
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| AJAX guardar opciones
+|--------------------------------------------------------------------------
+*/
+
+add_action('wp_ajax_alcastromol_save_tailwind_cache_options', function () {
+
+ if (!current_user_can('manage_options')) {
+ wp_send_json_error('No tienes permisos para guardar opciones.');
+ }
+
+ check_ajax_referer('alcastromol_tailwind_cache_nonce', 'nonce');
+
+ $raw_options = $_POST['options'] ?? [];
+
+ if (!is_array($raw_options)) {
+ $raw_options = [];
+ }
+
+ $options = alcastromol_save_cache_options($raw_options);
+
+ wp_send_json_success([
+ 'message' => 'Opciones guardadas',
+ 'options' => $options,
+ ]);
+
+});
+
+
+/*
+|--------------------------------------------------------------------------
+| AJAX generar cache
+|--------------------------------------------------------------------------
+*/
+
+add_action('wp_ajax_alcastromol_generate_tailwind_cache', function () {
+
+ if (!current_user_can('manage_options')) {
+ wp_send_json_error('No tienes permisos para generar el cache.');
+ }
+
+ check_ajax_referer('alcastromol_tailwind_cache_nonce', 'nonce');
+
+ $result = alcastromol_generate_full_cache();
+
+ wp_send_json_success([
+ 'message' => 'Cache generada',
+ 'total' => $result['total'],
+ 'products' => $result['products'],
+ 'oxygen_templates' => $result['oxygen_templates'],
+ 'generated' => $result['generated'],
+ 'failed' => $result['failed'],
+ 'failed_urls' => $result['failed_urls'],
+ ]);
+
+});
+
+
+/*
+|--------------------------------------------------------------------------
+| AJAX eliminar cache
+|--------------------------------------------------------------------------
+*/
+
+add_action('wp_ajax_alcastromol_delete_tailwind_cache', function () {
+
+ if (!current_user_can('manage_options')) {
+ wp_send_json_error('No tienes permisos para eliminar el cache.');
+ }
+
+ check_ajax_referer('alcastromol_tailwind_cache_nonce', 'nonce');
+
+ $deleted = alcastromol_delete_all_cache();
+
+ wp_send_json_success([
+ 'message' => 'Cache eliminado',
+ 'deleted' => $deleted,
+ ]);
+
+});
+
+
+/*
+|--------------------------------------------------------------------------
+| AJAX generar cache por tipo de contenido
+|--------------------------------------------------------------------------
+*/
+
+add_action('wp_ajax_alcastromol_generate_tailwind_cache_target', function () {
+
+ if (!current_user_can('manage_options')) {
+ wp_send_json_error('No tienes permisos para generar este cache.');
+ }
+
+ check_ajax_referer('alcastromol_tailwind_cache_nonce', 'nonce');
+
+ $target_type = sanitize_key($_POST['target_type'] ?? '');
+ $target_name = sanitize_key($_POST['target_name'] ?? '');
+
+ $allowed = ['home', 'post_type', 'taxonomy', 'oxygen_templates', 'authors'];
+
+ if (!in_array($target_type, $allowed, true)) {
+ wp_send_json_error('Tipo de cache inválido.');
+ }
+
+ $result = alcastromol_generate_cache_by_target($target_type, $target_name);
+
+ wp_send_json_success([
+ 'message' => 'Cache generado',
+ 'target_type' => $target_type,
+ 'target_name' => $target_name,
+ 'total' => $result['total'],
+ 'generated' => $result['generated'],
+ 'failed' => $result['failed'],
+ 'failed_urls' => $result['failed_urls'],
+ 'count' => $result['count'],
+ ]);
+
+});
+
+
+/*
+|--------------------------------------------------------------------------
+| AJAX eliminar cache por tipo de contenido
+|--------------------------------------------------------------------------
+*/
+
+add_action('wp_ajax_alcastromol_delete_tailwind_cache_target', function () {
+
+ if (!current_user_can('manage_options')) {
+ wp_send_json_error('No tienes permisos para eliminar este cache.');
+ }
+
+ check_ajax_referer('alcastromol_tailwind_cache_nonce', 'nonce');
+
+ $target_type = sanitize_key($_POST['target_type'] ?? '');
+ $target_name = sanitize_key($_POST['target_name'] ?? '');
+
+ $allowed = ['home', 'post_type', 'taxonomy', 'oxygen_templates', 'authors'];
+
+ if (!in_array($target_type, $allowed, true)) {
+ wp_send_json_error('Tipo de cache inválido.');
+ }
+
+ $deleted = alcastromol_delete_cache_by_target($target_type, $target_name);
+
+ wp_send_json_success([
+ 'message' => 'Cache eliminado',
+ 'target_type' => $target_type,
+ 'target_name' => $target_name,
+ 'deleted' => $deleted,
+ 'count' => alcastromol_count_cache_files_by_target($target_type, $target_name),
+ ]);
+
+});
+
+
+/*
+|--------------------------------------------------------------------------
+| Página herramientas
+|--------------------------------------------------------------------------
+*/
+
+add_action('admin_menu', function () {
+
+ add_management_page(
+ 'Tailwind Cache',
+ 'Tailwind Cache',
+ 'manage_options',
+ 'tailwind-cache',
+ 'alcastromol_tailwind_tools_page'
+ );
+
+});
+
+
+function alcastromol_tailwind_tools_page() {
+
+ $options = alcastromol_get_cache_options();
+
+ $post_types = alcastromol_detect_cacheable_post_types();
+
+ $taxonomies = alcastromol_detect_cacheable_taxonomies();
+
+ $nonce = wp_create_nonce('alcastromol_tailwind_cache_nonce');
+
+?>
+
+
+
+
Generar Cache Tailwind
+
+
+ Selecciona qué contenido quieres cachear para que Tailwind detecte clases de Gutenberg,
+ WooCommerce, CPTs, taxonomías y templates de Oxygen.
+
+
+
+
+
Contenido cacheable detectado
+
+
+
+
+
+
+
+ Guardar selección
+
+
+
+ Generar cache seleccionado
+
+
+
+ Eliminar todo el cache
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Inicio - Alejandro Castro
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Te decimos cómo apareces en Google y en las respuestas de IA, y los pasos exactos para convertir esa visibilidad en crecimiento.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ ¡HEY!
+
+
+
+ SOY ALEJANDRO.
+
+
+ Desarrollador web y especialista SEO con más de creando sitios que no solo se ven bien, sino que también están preparados para posicionarse, convertir y crecer.
+
+
+ Trabajo con WordPress, WooCommerce y desarrollo personalizado, combinando diseño, programación, rendimiento, SEO técnico, automatizaciones e integraciones.
+
+
+ Mi enfoque une desarrollo web + SEO + datos. He gestionado proyectos que lograron multiplicar más de 4X su tráfico orgánico en aproximadamente un año.
+
+
+
+
+
+
+
+
+
+ para que se vean bien
+
+
+
+
+
+ Los construyo para que sean rápidos, visibles y capaces de generar negocio
+
+
+
+
+
+
+
+
+
+
+
+ Dos formas de trabajar conmigo
+
+
+
+
+ Puedes trabajar conmigo para que lo hagamos por ti , o puedes aprender paso a paso para hacerlo tú mismo. Tú eliges el camino.
+
+
+
+
+
+
+
+
Lo hacemos por ti
+
Servicios digitales.
+
Para empresas que necesitan ejecutar, optimizar y crecer sin tener que resolver toda la parte técnica internamente.
+
+ Desarrollo web
+ SEO y visibilidad en IA
+ E-commerce
+ Automatización e integraciones
+ Rendimiento y seguridad
+
+
+ Conoce mis servicios
+ →
+
+
+
+
+
+
+
+
+
Te enseño a hacerlo
+
Academia.
+
Formación práctica para profesionales, emprendedores y equipos que quieren dominar desarrollo web, SEO, automatización e IA.
+
+ Cursos paso a paso
+ Recursos y plantillas
+ Formación para equipos
+ Experiencia basada en proyectos reales
+
+
+ Explora la academia
+ →
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Resultados
+
+
+
+ Proyectos reales que generan crecimiento.
+
+
+ Desarrollo, SEO, automatización y estrategia trabajando juntos para lograr resultados medibles en negocios reales.
+
+
+
+
+
+
+
+
+ +4X
+ Tráfico orgánico
+ Crecimiento promedio en proyectos SEO en ~1 año.
+
+
+
+
+
+ +8 años
+ Experiencia
+ Desarrollando y posicionando soluciones digitales.
+
+
+
+
+
+ 360°
+ Desarrollo + SEO + Datos
+ Una estrategia completa para crecer.
+
+
+
+
+
+ 98/100
+ Rendimiento web
+ Sitios rápidos, optimizados y listos para escalar.
+
+
+
+
+
+
+
+
+
+
+
+ Resultados por industria
+
+
+
+ Crecimiento real en industrias diferentes.
+
+
+ No importa si tu negocio es B2B o B2C. Desarrollo, SEO, automatización y estrategia se adaptan a cada industria para convertir tecnología y visibilidad en resultados.
+
+
+
+
+
+
+
+
+ +16
+ Industrias atendidas
+
+
+
+
+
+
+
+ +50
+ Proyectos ejecutados
+
+
+
+
+
+
+
+ Resultados medibles
+ En el corto y mediano plazo
+
+
+
+
+
+
+
+ Todos
+ B2B
+ B2C
+
+
+
+
+
+
+
+ B2C
+
+
Industria Educativa
+
+58%
+
De crecimiento en inscripciones
+
+
+ 6 meses
+
+
+
+
+ B2B
+
+
Industria Retail
+
+23%
+
De crecimiento en MQL de LinkedIn
+
+
+ 2 meses
+
+
+
+
+ B2C
+
+
Industria de la Salud
+
+100%
+
De automatización en CRM para atención a leads y pacientes
+
+
+
+
+ B2C
+
+
Industria Farmacéutica
+
+500%
+
De crecimiento en clics del sitio web
+
+
+ 8 meses
+
+
+
+
+ B2B
+
+
Industria y equipamiento industrial
+
+67%
+
De crecimiento orgánico en fichas de catálogo
+
+
+ 7 meses
+
+
+
+
+ B2B
+
+
Tecnología, software e inteligencia artificial
+
+184%
+
De crecimiento en ventas de demos calificadas
+
+
+ 5 meses
+
+
+
+
+ B2B
+
+
Finanzas, inversión y arrendamiento
+
+93%
+
De crecimiento orgánico en leads de inversión
+
+
+ 4 meses
+
+
+
+
+ B2B
+
+
Bienes raíces, arquitectura y construcción
+
+71%
+
De crecimiento en ventas de citas de preventa
+
+
+ 6 meses
+
+
+
+
+ B2C
+
+
Turismo, hotelería y hospitalidad
+
+146%
+
De crecimiento en ventas de reservas directas
+
+
+ 8 meses
+
+
+
+
+ B2C
+
+
Salud, medicina y bienestar
+
+118%
+
De crecimiento orgánico en citas de consulta
+
+
+ 5 meses
+
+
+
+
+ B2B
+
+
Marketing, publicidad y servicios digitales
+
+52%
+
De crecimiento en ventas de retainer
+
+
+ 3 meses
+
+
+
+
+ B2B
+
+
Eventos, congresos y entretenimiento
+
+207%
+
De crecimiento orgánico en registros al evento
+
+
+ 2 meses
+
+
+
+
+ B2B
+
+
Logística, transporte y comercio exterior
+
+89%
+
De crecimiento en ventas de cotizaciones cerradas
+
+
+ 6 meses
+
+
+
+
+ B2C
+
+
Deportes
+
+161%
+
De crecimiento orgánico en inscripciones a membresías
+
+
+ 4 meses
+
+
+
+
+ B2C
+
+
Medios, cultura y publicaciones
+
+44%
+
De crecimiento en ventas de suscripciones
+
+
+ 9 meses
+
+
+
+
+ B2C
+
+
Gaming y entretenimiento digital
+
+233%
+
De crecimiento orgánico en registros de jugadores
+
+
+ 3 meses
+
+
+
+
+
+
+ Ver resultados de todas las industrias
+ →
+
+
+
+
Otras industrias en las que he generado resultados
+
+
+
+ Industrial
+
+
+
+
+ Tecnología
+
+
+
+
+ Finanzas
+
+
+
+
+ Construcción
+
+
+
+
+ Turismo
+
+
+
+
+ Bienestar
+
+
+
+
+ Marketing
+
+
+
+
+ Eventos
+
+
+
+
+ Logística
+
+
+
+
+ Deportes
+
+
+
+
+ Medios
+
+
+
+
+ Gaming
+
+
+
+
+
+
+
+
+
+
+
+ Hablemos
+
+
+
+ ¿Listo para impulsartu próximo proyecto?
+
+
+ Cuéntame tu idea y conversemos sobre cómo llevarla a resultados reales con desarrollo, SEO y automatización.
+
+
+
+ Chatear ahora
+ →
+
+
+
+
+
+
+ Respuesta rápida
+
+
+
+
+
+ Asesoría personalizada
+
+
+
+
+
+ Sin compromiso
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Desarrollo, SEO, automatización y estrategia digital para negocios reales.
+
+
+
+ Sitios web de alto rendimiento
+
+
+
+ Estrategias SEO medibles
+
+
+
+ Automatización de procesos
+
+
+
+ Acompañamiento personalizado
+
+
+
+
+
+ Navegación
+
+
+
+
+ Servicios
+
+
+
+
+
+
+
+
+
+
Recibe ideas y recursos para hacer crecer tu negocio.
+
Contenido práctico de desarrollo, SEO y automatización, directo a tu correo.
+
+
+
+
+
+
© 2026 Alcastromol. Todos los derechos reservados.
+
+ Aviso de privacidad
+ Términos y condiciones
+ Política de cookies
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Whatssap "Conversemos"
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/functions/tailwindcss/tailwind.config.js b/functions/tailwindcss/tailwind.config.js
index 8fd25f8..6ec260f 100644
--- a/functions/tailwindcss/tailwind.config.js
+++ b/functions/tailwindcss/tailwind.config.js
@@ -45,9 +45,25 @@ module.exports = {
"2": "#333333",
"3": "#B0B0B0"
},
- "dark": "#333333",
- "red-brand": "#DB2729",
- "black-brand": "#242424"
+ "brand": {
+ "background": "#061018",
+ "foreground": "#F4FBFC",
+ "soft": "#A8BDC7",
+ "muted": "#718894",
+ "border": "#243746",
+ "accent-soft": "#97E0E5",
+ "accent": "#00FFE6",
+ "accent-blue": "#00BDFF"
+ }
+ },
+ "backgroundImage": {
+ "brand-gradient": "linear-gradient(90deg, #00FFE6 0%, #00BDFF 100%)"
+ },
+ "fontFamily": {
+ "sans": [
+ "Manrope",
+ "sans-serif"
+ ]
}
}
},
diff --git a/functions/tailwindcss/tailwindcss.php.bak-20260826-admin-navigation b/functions/tailwindcss/tailwindcss.php.bak-20260826-admin-navigation
new file mode 100644
index 0000000..ccb96ee
--- /dev/null
+++ b/functions/tailwindcss/tailwindcss.php.bak-20260826-admin-navigation
@@ -0,0 +1,1479 @@
+ [
+ './cache/*.{php,html,js}',
+ ],
+
+ 'theme' => [
+ 'screens' => [
+ 'xxxxl' => [ 'max' => '1701px' ],
+ 'xxxl' => [ 'max' => '1550px' ],
+ 'xxl' => [ 'max' => '1439px' ],
+ 'xl' => [ 'max' => '1119px' ],
+ 'lg' => [ 'max' => '1024px' ],
+ 'md' => [ 'max' => '767px' ],
+ 'sm' => [ 'max' => '479px' ],
+ 'ssm' => [ 'max' => '380px' ],
+ ],
+
+ 'container' => [
+ 'center' => true,
+ 'padding' => '1rem',
+ 'screens' => [
+ 'DEFAULT' => '1702px',
+ ],
+ ],
+
+ 'extend' => [
+ 'colors' => [
+ 'color' => [
+ '1' => '#004983',
+ '2' => '#333333',
+ '3' => '#B0B0B0',
+ ],
+ 'dark' => '#333333',
+ 'red-brand' => '#DB2729',
+ 'black-brand' => '#242424',
+ ],
+ ],
+ ],
+
+ 'plugins' => [],
+ ];
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Obtener configuración de Tailwind
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_tailwind_get_settings() {
+
+ $defaults = alcastromol_tailwind_default_settings();
+ $settings = get_option(ALCASTROMOL_TAILWIND_SETTINGS_OPTION, []);
+
+ if (!is_array($settings)) {
+ $settings = [];
+ }
+
+ $settings = wp_parse_args($settings, $defaults);
+
+ if (empty($settings['content']) || !is_array($settings['content'])) {
+ $settings['content'] = $defaults['content'];
+ }
+
+ if (empty($settings['theme']) || !is_array($settings['theme'])) {
+ $settings['theme'] = $defaults['theme'];
+ }
+
+ if (!isset($settings['plugins']) || !is_array($settings['plugins'])) {
+ $settings['plugins'] = [];
+ }
+
+ return $settings;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Generar archivo tailwind.config.js
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_tailwind_generate_config_file() {
+
+ $settings = alcastromol_tailwind_get_settings();
+
+ $config = [
+ 'content' => $settings['content'],
+ 'theme' => $settings['theme'],
+ 'plugins' => $settings['plugins'],
+ ];
+
+ $json = wp_json_encode(
+ $config,
+ JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
+ );
+
+ if (!$json) {
+ return [
+ 'success' => false,
+ 'message' => 'No se pudo convertir la configuración de Tailwind a JSON.',
+ ];
+ }
+
+ $js = "/** @type {import('tailwindcss').Config} */\n";
+ $js .= "module.exports = " . $json . ";\n";
+
+ $config_dir = dirname(ALCASTROMOL_TAILWIND_CONFIG);
+
+ if (!file_exists($config_dir)) {
+ wp_mkdir_p($config_dir);
+ }
+
+ if (!is_dir($config_dir) || !is_writable($config_dir)) {
+ return [
+ 'success' => false,
+ 'message' => 'La carpeta del archivo tailwind.config.js no existe o no tiene permisos de escritura: ' . $config_dir,
+ ];
+ }
+
+ $written = file_put_contents(ALCASTROMOL_TAILWIND_CONFIG, $js);
+
+ if ($written === false) {
+ return [
+ 'success' => false,
+ 'message' => 'No se pudo escribir el archivo tailwind.config.js.',
+ ];
+ }
+
+ clearstatcache(true, ALCASTROMOL_TAILWIND_CONFIG);
+
+ return [
+ 'success' => true,
+ 'message' => 'tailwind.config.js generado correctamente.',
+ 'file' => ALCASTROMOL_TAILWIND_CONFIG,
+ 'size' => file_exists(ALCASTROMOL_TAILWIND_CONFIG) ? size_format(filesize(ALCASTROMOL_TAILWIND_CONFIG)) : '',
+ ];
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Obtener modo actual
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_get_tailwind_mode() {
+
+ $mode = get_option(ALCASTROMOL_TAILWIND_MODE_OPTION, 'production');
+
+ if (!in_array($mode, ['developer', 'production'], true)) {
+ $mode = 'production';
+ }
+
+ return $mode;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Validar si está en modo developer
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_is_tailwind_developer_mode() {
+
+ return alcastromol_get_tailwind_mode() === 'developer';
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Detectar si la URL actual contiene algún parámetro del builder
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_request_has_builder_param($params) {
+
+ foreach ($params as $param) {
+ if (isset($_GET[$param]) || isset($_POST[$param]) || isset($_REQUEST[$param])) {
+ return true;
+ }
+ }
+
+ return false;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Detectar Oxygen Builder
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_is_oxygen_builder() {
+
+ $oxygen_params = [
+ 'ct_builder',
+ 'ct_inner',
+ 'oxygen_iframe',
+ 'oxygen_builder',
+ 'ct_sign_sha256',
+ 'ct_template',
+ ];
+
+ if (alcastromol_request_has_builder_param($oxygen_params)) {
+ return true;
+ }
+
+ $request_uri = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])) : '';
+
+ if (
+ strpos($request_uri, 'ct_builder') !== false ||
+ strpos($request_uri, 'ct_inner') !== false ||
+ strpos($request_uri, 'oxygen_iframe') !== false ||
+ strpos($request_uri, 'oxygen_builder') !== false
+ ) {
+ return true;
+ }
+
+ return false;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Detectar Breakdance Builder
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_is_breakdance_builder() {
+
+ $breakdance_params = [
+ 'breakdance',
+ 'breakdance_builder',
+ 'breakdance_iframe',
+ 'breakdance_preview',
+ 'breakdance_open',
+ 'breakdance_canvas',
+ 'breakdance_editor',
+ ];
+
+ if (alcastromol_request_has_builder_param($breakdance_params)) {
+ return true;
+ }
+
+ $request_uri = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])) : '';
+
+ if (
+ strpos($request_uri, 'breakdance') !== false ||
+ strpos($request_uri, 'breakdance_builder') !== false ||
+ strpos($request_uri, 'breakdance_iframe') !== false ||
+ strpos($request_uri, 'breakdance_preview') !== false
+ ) {
+ return true;
+ }
+
+ return false;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Detectar contexto de builder para Tailwind
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_is_tailwind_builder_context() {
+
+ if (alcastromol_is_oxygen_builder()) {
+ return true;
+ }
+
+ if (alcastromol_is_breakdance_builder()) {
+ return true;
+ }
+
+ return false;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Generar HTML del CDN Tailwind con configuración dinámica
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_tailwind_cdn_script_html() {
+
+ $settings = alcastromol_tailwind_get_settings();
+
+ /*
+ * Para el CDN solo usamos theme.
+ * content no aplica porque el CDN genera clases en el navegador.
+ */
+ $cdn_config = [
+ 'theme' => $settings['theme'],
+ ];
+
+ ob_start();
+ ?>
+
+
+
+
+
+
+
+
+|--------------------------------------------------------------------------
+|
+| Oxygen puede imprimir sus HEADER ASSETS después de la cola normal de
+| WordPress. Por eso PHP_INT_MAX en wp_enqueue_scripts no siempre basta.
+| Este buffer elimina la impresión previa del CSS productivo y lo inserta
+| justo antes de , dejando Tailwind como el último CSS del header.
+|
+*/
+
+function alcastromol_tailwind_start_head_buffer() {
+
+ if (is_admin()) {
+ return;
+ }
+
+ if (alcastromol_is_tailwind_builder_context()) {
+ return;
+ }
+
+ if (alcastromol_is_tailwind_developer_mode()) {
+ return;
+ }
+
+ if (!file_exists(ALCASTROMOL_TAILWIND_OUTPUT_CSS)) {
+ return;
+ }
+
+ ob_start('alcastromol_tailwind_move_css_before_head_close');
+
+}
+
+add_action('template_redirect', 'alcastromol_tailwind_start_head_buffer', 0);
+
+
+function alcastromol_tailwind_move_css_before_head_close($html) {
+
+ if (!is_string($html) || stripos($html, '') === false) {
+ return $html;
+ }
+
+ $css_path = ALCASTROMOL_TAILWIND_OUTPUT_CSS;
+ $css_url = ALCASTROMOL_TAILWIND_BASE_URL . 'css-production/styles-tailwind.css';
+
+ if (!file_exists($css_path)) {
+ return $html;
+ }
+
+ $version = filemtime($css_path);
+
+ /*
+ * Remover la impresión previa hecha por wp_enqueue_style().
+ */
+ $html = preg_replace(
+ '# ]+id=[\"\']alcastromol-tailwind-css[\"\'][^>]*>\s*#i',
+ '',
+ $html
+ );
+
+ /*
+ * Remover una posible impresión previa sin id, por si algún optimizador
+ * modificó el atributo id pero conservó la URL del archivo.
+ */
+ $html = preg_replace(
+ '# ]+href=[\"\'][^\"\']*/tailwindcss/css-production/styles-tailwind\.css[^\"\']*[\"\'][^>]*>\s*#i',
+ '',
+ $html
+ );
+
+ $tailwind_link = sprintf(
+ ' ' . "\n",
+ esc_url($css_url . '?ver=' . $version)
+ );
+
+ return str_ireplace('', $tailwind_link . '', $html);
+
+}
+
+
+
+/*
+|--------------------------------------------------------------------------
+| Cargar CDN en front end normal solo en modo Developer
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_tailwind_front_cdn() {
+
+ if (is_admin()) {
+ return;
+ }
+
+ /*
+ * Si estamos dentro de Oxygen o Breakdance,
+ * esta carga la controla alcastromol_tailwind_builder_iframe_cdn().
+ */
+ if (alcastromol_is_tailwind_builder_context()) {
+ return;
+ }
+
+ if (!alcastromol_is_tailwind_developer_mode()) {
+ return;
+ }
+
+ alcastromol_tailwind_cdn_script();
+
+}
+
+add_action('wp_head', 'alcastromol_tailwind_front_cdn', PHP_INT_MAX);
+
+
+/*
+|--------------------------------------------------------------------------
+| Cargar CDN en admin solo dentro de Oxygen / Breakdance
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_tailwind_admin_cdn() {
+
+ /*
+ * Solo admin.
+ */
+ if (!is_admin()) {
+ return;
+ }
+
+ /*
+ * Admin normal: no carga CDN.
+ */
+ if (!alcastromol_is_tailwind_builder_context()) {
+ return;
+ }
+
+ /*
+ * Admin dentro del builder: sí carga CDN.
+ */
+ alcastromol_tailwind_cdn_script();
+
+}
+
+add_action('admin_head', 'alcastromol_tailwind_admin_cdn', PHP_INT_MAX);
+
+
+/*
+|--------------------------------------------------------------------------
+| Cargar CDN en iframe/front de Oxygen / Breakdance
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_tailwind_builder_iframe_cdn() {
+
+ /*
+ * Esta parte aplica al iframe/front del builder,
+ * no al admin normal.
+ */
+ if (is_admin()) {
+ return;
+ }
+
+ /*
+ * Front normal: no carga CDN en producción.
+ */
+ if (!alcastromol_is_tailwind_builder_context()) {
+ return;
+ }
+
+ /*
+ * Dentro del iframe del builder: sí carga CDN.
+ */
+ alcastromol_tailwind_cdn_script();
+
+}
+
+add_action('wp_head', 'alcastromol_tailwind_builder_iframe_cdn', PHP_INT_MAX);
+
+
+/*
+|--------------------------------------------------------------------------
+| Obtener binario Standalone CLI de Tailwind
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_tailwind_get_cli_path() {
+
+ $candidates = [];
+
+ if (defined('PHP_OS_FAMILY') && PHP_OS_FAMILY === 'Windows') {
+ $candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'bin/tailwindcss-windows-x64.exe';
+ $candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'bin/tailwindcss.exe';
+ $candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'tailwindcss-windows-x64.exe';
+ $candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'tailwindcss.exe';
+ } elseif (defined('PHP_OS_FAMILY') && PHP_OS_FAMILY === 'Darwin') {
+ $candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'bin/tailwindcss-macos-x64';
+ $candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'bin/tailwindcss-macos-arm64';
+ $candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'bin/tailwindcss';
+ $candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'tailwindcss-macos-x64';
+ $candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'tailwindcss-macos-arm64';
+ $candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'tailwindcss';
+ } else {
+ $candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'bin/tailwindcss-linux-x64';
+ $candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'bin/tailwindcss-linux-arm64';
+ $candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'bin/tailwindcss';
+ $candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'tailwindcss-linux-x64';
+ $candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'tailwindcss-linux-arm64';
+ $candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'tailwindcss';
+ }
+
+ $candidates = apply_filters('alcastromol_tailwind_cli_candidates', $candidates);
+
+ foreach ($candidates as $candidate) {
+ if (is_string($candidate) && file_exists($candidate) && is_file($candidate)) {
+ return $candidate;
+ }
+ }
+
+ return false;
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Validar si proc_open está disponible
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_tailwind_can_run_processes() {
+
+ if (!function_exists('proc_open')) {
+ return false;
+ }
+
+ $disabled = ini_get('disable_functions');
+
+ if (!$disabled) {
+ return true;
+ }
+
+ $disabled_functions = array_map('trim', explode(',', $disabled));
+
+ return !in_array('proc_open', $disabled_functions, true);
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Compilar Tailwind v3 con Standalone CLI
+|--------------------------------------------------------------------------
+*/
+
+function alcastromol_compile_tailwind_standalone_cli() {
+
+ if (alcastromol_get_tailwind_mode() !== 'production') {
+ return [
+ 'success' => false,
+ 'message' => 'Tailwind solo se puede compilar desde este botón cuando el modo productivo está activo.',
+ ];
+ }
+
+ if (!file_exists(ALCASTROMOL_TAILWIND_INPUT_CSS)) {
+ return [
+ 'success' => false,
+ 'message' => 'No existe el archivo de entrada: ' . ALCASTROMOL_TAILWIND_INPUT_CSS,
+ ];
+ }
+
+ /*
+ * Antes de compilar, regeneramos tailwind.config.js
+ * usando la configuración guardada desde el admin.
+ */
+ $config_result = alcastromol_tailwind_generate_config_file();
+
+ if (empty($config_result['success'])) {
+ return [
+ 'success' => false,
+ 'message' => 'No se pudo generar tailwind.config.js antes de compilar. ' . ($config_result['message'] ?? ''),
+ ];
+ }
+
+ if (!file_exists(ALCASTROMOL_TAILWIND_CONFIG)) {
+ return [
+ 'success' => false,
+ 'message' => 'No existe el archivo de configuración: ' . ALCASTROMOL_TAILWIND_CONFIG,
+ ];
+ }
+
+ $output_dir = dirname(ALCASTROMOL_TAILWIND_OUTPUT_CSS);
+
+ if (!file_exists($output_dir)) {
+ wp_mkdir_p($output_dir);
+ }
+
+ if (!is_dir($output_dir) || !is_writable($output_dir)) {
+ return [
+ 'success' => false,
+ 'message' => 'La carpeta de salida no existe o no tiene permisos de escritura: ' . $output_dir,
+ ];
+ }
+
+ $cli_path = alcastromol_tailwind_get_cli_path();
+
+ if (!$cli_path) {
+ return [
+ 'success' => false,
+ 'message' => 'No se encontró el binario Standalone CLI de Tailwind. Colócalo en functions/tailwindcss/bin/tailwindcss-linux-x64 o functions/tailwindcss/bin/tailwindcss.',
+ ];
+ }
+
+ if (!is_executable($cli_path) && (!defined('PHP_OS_FAMILY') || PHP_OS_FAMILY !== 'Windows')) {
+ @chmod($cli_path, 0755);
+ }
+
+ if (!is_executable($cli_path) && (!defined('PHP_OS_FAMILY') || PHP_OS_FAMILY !== 'Windows')) {
+ return [
+ 'success' => false,
+ 'message' => 'El binario de Tailwind existe, pero no tiene permisos de ejecución: ' . $cli_path,
+ ];
+ }
+
+ if (!alcastromol_tailwind_can_run_processes()) {
+ return [
+ 'success' => false,
+ 'message' => 'PHP no puede ejecutar procesos porque proc_open no está disponible o está deshabilitado en el servidor.',
+ ];
+ }
+
+ $command_parts = [
+ $cli_path,
+ '-i', ALCASTROMOL_TAILWIND_INPUT_CSS,
+ '-o', ALCASTROMOL_TAILWIND_OUTPUT_CSS,
+ '-c', ALCASTROMOL_TAILWIND_CONFIG,
+ '--minify',
+ ];
+
+ $command = implode(' ', array_map('escapeshellarg', $command_parts));
+
+ $descriptor_spec = [
+ 0 => ['pipe', 'r'],
+ 1 => ['pipe', 'w'],
+ 2 => ['pipe', 'w'],
+ ];
+
+ $pipes = [];
+
+ $process = proc_open(
+ $command,
+ $descriptor_spec,
+ $pipes,
+ ALCASTROMOL_TAILWIND_BASE_DIR
+ );
+
+ if (!is_resource($process)) {
+ return [
+ 'success' => false,
+ 'message' => 'No se pudo iniciar el proceso de compilación de Tailwind.',
+ ];
+ }
+
+ fclose($pipes[0]);
+
+ $stdout = stream_get_contents($pipes[1]);
+ fclose($pipes[1]);
+
+ $stderr = stream_get_contents($pipes[2]);
+ fclose($pipes[2]);
+
+ $exit_code = proc_close($process);
+
+ clearstatcache(true, ALCASTROMOL_TAILWIND_OUTPUT_CSS);
+
+ if ($exit_code !== 0) {
+ return [
+ 'success' => false,
+ 'message' => 'Tailwind no pudo compilar. Código de salida: ' . $exit_code,
+ 'stdout' => trim($stdout),
+ 'stderr' => trim($stderr),
+ 'command' => $command,
+ 'cli_path' => $cli_path,
+ ];
+ }
+
+ if (!file_exists(ALCASTROMOL_TAILWIND_OUTPUT_CSS)) {
+ return [
+ 'success' => false,
+ 'message' => 'Tailwind terminó sin error, pero no se generó el archivo CSS de salida.',
+ 'stdout' => trim($stdout),
+ 'stderr' => trim($stderr),
+ ];
+ }
+
+ return [
+ 'success' => true,
+ 'message' => 'Tailwind v3 compilado correctamente con Standalone CLI.',
+ 'stdout' => trim($stdout),
+ 'stderr' => trim($stderr),
+ 'cli_path' => $cli_path,
+ 'output_file' => ALCASTROMOL_TAILWIND_OUTPUT_CSS,
+ 'file_size' => size_format(filesize(ALCASTROMOL_TAILWIND_OUTPUT_CSS)),
+ 'modified' => date_i18n('d/m/Y g:i a', filemtime(ALCASTROMOL_TAILWIND_OUTPUT_CSS)),
+ ];
+
+}
+
+
+/*
+|--------------------------------------------------------------------------
+| Guardar modo desde admin
+|--------------------------------------------------------------------------
+*/
+
+add_action('admin_post_alcastromol_save_tailwind_mode', function () {
+
+ if (!current_user_can('manage_options')) {
+ wp_die('No tienes permisos para hacer esto.');
+ }
+
+ check_admin_referer('alcastromol_tailwind_mode_nonce');
+
+ $mode = isset($_POST['tailwind_mode']) ? sanitize_text_field($_POST['tailwind_mode']) : 'production';
+
+ if (!in_array($mode, ['developer', 'production'], true)) {
+ $mode = 'production';
+ }
+
+ update_option(ALCASTROMOL_TAILWIND_MODE_OPTION, $mode);
+
+ wp_redirect(
+ add_query_arg(
+ [
+ 'page' => 'alcastromol-tailwind-mode',
+ 'updated' => 'true',
+ ],
+ admin_url('tools.php')
+ )
+ );
+
+ exit;
+
+});
+
+
+/*
+|--------------------------------------------------------------------------
+| Guardar configuración de Tailwind desde admin
+|--------------------------------------------------------------------------
+*/
+
+add_action('admin_post_alcastromol_save_tailwind_settings', function () {
+
+ if (!current_user_can('manage_options')) {
+ wp_die('No tienes permisos para hacer esto.');
+ }
+
+ check_admin_referer('alcastromol_tailwind_settings_nonce');
+
+ $content_raw = isset($_POST['tailwind_content']) ? wp_unslash($_POST['tailwind_content']) : '';
+ $theme_raw = isset($_POST['tailwind_theme']) ? wp_unslash($_POST['tailwind_theme']) : '';
+
+ $content = json_decode($content_raw, true);
+ $theme = json_decode($theme_raw, true);
+
+ if (!is_array($content)) {
+ wp_redirect(
+ add_query_arg(
+ [
+ 'page' => 'alcastromol-tailwind-mode',
+ 'settings_error' => 'content_json',
+ ],
+ admin_url('tools.php')
+ )
+ );
+
+ exit;
+ }
+
+ if (!is_array($theme)) {
+ wp_redirect(
+ add_query_arg(
+ [
+ 'page' => 'alcastromol-tailwind-mode',
+ 'settings_error' => 'theme_json',
+ ],
+ admin_url('tools.php')
+ )
+ );
+
+ exit;
+ }
+
+ $settings = [
+ 'content' => $content,
+ 'theme' => $theme,
+ 'plugins' => [],
+ ];
+
+ update_option(ALCASTROMOL_TAILWIND_SETTINGS_OPTION, $settings);
+
+ $result = alcastromol_tailwind_generate_config_file();
+
+ set_transient(
+ 'alcastromol_tailwind_config_result_' . get_current_user_id(),
+ $result,
+ 120
+ );
+
+ wp_redirect(
+ add_query_arg(
+ [
+ 'page' => 'alcastromol-tailwind-mode',
+ 'settings_updated' => !empty($result['success']) ? 'true' : 'false',
+ ],
+ admin_url('tools.php')
+ )
+ );
+
+ exit;
+
+});
+
+
+/*
+|--------------------------------------------------------------------------
+| Compilar Tailwind desde admin
+|--------------------------------------------------------------------------
+*/
+
+add_action('admin_post_alcastromol_compile_tailwind_cli', function () {
+
+ if (!current_user_can('manage_options')) {
+ wp_die('No tienes permisos para hacer esto.');
+ }
+
+ check_admin_referer('alcastromol_compile_tailwind_cli_nonce');
+
+ $result = alcastromol_compile_tailwind_standalone_cli();
+
+ set_transient(
+ 'alcastromol_tailwind_compile_result_' . get_current_user_id(),
+ $result,
+ 120
+ );
+
+ wp_redirect(
+ add_query_arg(
+ [
+ 'page' => 'alcastromol-tailwind-mode',
+ 'compiled' => !empty($result['success']) ? 'true' : 'false',
+ ],
+ admin_url('tools.php')
+ )
+ );
+
+ exit;
+
+});
+
+
+/*
+|--------------------------------------------------------------------------
+| Página admin
+|--------------------------------------------------------------------------
+*/
+
+add_action('admin_menu', function () {
+
+ add_management_page(
+ 'Tailwind Modo',
+ 'Tailwind Modo',
+ 'manage_options',
+ 'alcastromol-tailwind-mode',
+ 'alcastromol_tailwind_mode_page'
+ );
+
+});
+
+
+function alcastromol_tailwind_mode_page() {
+
+ $mode = alcastromol_get_tailwind_mode();
+ $cli_path = alcastromol_tailwind_get_cli_path();
+
+ $tailwind_settings = alcastromol_tailwind_get_settings();
+
+ $compile_result = get_transient('alcastromol_tailwind_compile_result_' . get_current_user_id());
+
+ if ($compile_result) {
+ delete_transient('alcastromol_tailwind_compile_result_' . get_current_user_id());
+ }
+
+ $config_result = get_transient('alcastromol_tailwind_config_result_' . get_current_user_id());
+
+ if ($config_result) {
+ delete_transient('alcastromol_tailwind_config_result_' . get_current_user_id());
+ }
+
+ ?>
+
+
+
+
Modo Tailwind
+
+
+
+
Modo Tailwind actualizado correctamente.
+
+
+
+
+
+
+ Error: revisa que el JSON de configuración sea válido.
+
+ El problema está en Content.
+
+ El problema está en Theme.
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Archivo:
+
+
+
+
+
+
+ Tamaño:
+
+
+
+
+
+
+
Error al generar tailwind.config.js.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Tamaño:
+
+
+
+ Última modificación:
+
+
+
+
+
+
+
+
+
+
+
Error al compilar Tailwind.
+
+
+
+
Error:
+
+
+
+
+
Salida:
+
+
+
+
+
+
+
+
+ Selecciona cómo quieres cargar Tailwind en el sitio.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Configuración de Tailwind
+
+
+ Edita aquí la configuración principal de Tailwind. Desde esta configuración se genera automáticamente:
+
+
+
+ El script window.tailwind.config usado por el CDN.
+ El archivo físico tailwind.config.js usado para compilar en producción.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Estado actual
+
+
+
+
+ Modo activo: Developer
+
+
+
+
+
+ Área
+ Archivo cargado
+
+
+
+
+
+ Admin normal
+ No carga Tailwind CDN
+
+
+
+ Constructor Oxygen 6
+ CDN Tailwind con configuración generada desde admin
+
+
+
+ Constructor Breakdance
+ CDN Tailwind con configuración generada desde admin
+
+
+
+ Front end normal
+ CDN Tailwind con configuración generada desde admin
+
+
+
+ CSS productivo
+ No se carga en front end normal
+
+
+
+
+
+
+ Para compilar Tailwind con Standalone CLI, cambia primero a Modo productivo .
+
+
+
+
+
+
+ Modo activo: Productivo
+
+
+
+
+
+ Área
+ Archivo cargado
+
+
+
+
+
+ Admin normal
+ No carga Tailwind CDN
+
+
+
+ Constructor Oxygen 6
+ CDN Tailwind con configuración generada desde admin
+
+
+
+ Constructor Breakdance
+ CDN Tailwind con configuración generada desde admin
+
+
+
+ Front end normal
+ CSS compilado: styles-tailwind.css
+
+
+
+ CDN en front end normal
+ No se carga
+
+
+
+
+
+
+
Compilar Tailwind v3
+
+
+ Este botón compila Tailwind v3 minificado usando Standalone CLI , sin Node.js, npm ni npx.
+
+
+
+ Antes de compilar, el plugin vuelve a generar automáticamente el archivo tailwind.config.js
+ usando la configuración guardada arriba.
+
+
+
+
+
+ Binario detectado
+
+
+
+
+ No detectado
+
+
+
+
+
+ Archivo input
+
+
+
+
+ Archivo config
+
+
+
+
+
+ Existe —
+
+ —
+ modificado:
+
+
+
+ No existe todavía
+
+
+
+
+
+ Archivo output
+
+
+
+
+ Estado del CSS
+
+
+ Existe —
+
+ —
+ modificado:
+
+
+ No existe todavía
+
+
+
+
+
+
+
+
+
+ Falta subir el binario Standalone CLI. Para producción Linux, colócalo en:
+
+ functions/tailwindcss/bin/tailwindcss-linux-x64
+
+
+
+
+
+
+
+
+ 'disabled']); ?>
+
+
+
+
+
+
+
Notas
+
+
+ El CDN se imprime con prioridad PHP_INT_MAX en wp_head y admin_head.
+ Esto evita usar buffer, que puede romper Oxygen, Breakdance o la carga normal de WordPress.
+
+
+
+ Parámetros detectados para Oxygen:
+ ct_builder,
+ ct_inner,
+ oxygen_iframe,
+ oxygen_builder,
+ ct_sign_sha256,
+ ct_template.
+
+
+
+ Parámetros detectados para Breakdance:
+ breakdance,
+ breakdance_builder,
+ breakdance_iframe,
+ breakdance_preview,
+ breakdance_open,
+ breakdance_canvas,
+ breakdance_editor.
+
+
+
+ En modo productivo, el front end normal solo carga:
+ tailwindcss/css-production/styles-tailwind.css.
+
+
+
+ Dentro de Oxygen o Breakdance, tanto en modo developer como en modo productivo, se carga el CDN para poder visualizar clases nuevas dentro del constructor.
+
+
+
+ El archivo tailwind.config.js ya no se debe editar manualmente.
+ Ahora se genera desde la configuración guardada en esta pantalla.
+
+
+
+
+