Tutorial WordPress: Crear un layout tipo revista para el blog con CSS Grid areas

·

·

Introducción

Crear un layout tipo revista para el blog con CSS Grid areas aporta un resultado visual atractivo, modular y fácil de mantener. En este artículo encontrarás un tutorial completo para implementar un layout de revista en un tema de WordPress: desde la estructura HTML/PHP en la plantilla, el CSS con grid-template-areas, hasta consideraciones de rendimiento, imágenes y accesibilidad.

Visión general del layout

El objetivo es una portada tipo revista que combine:

Usaremos CSS Grid areas para declarar las posiciones semánticas de cada bloque y poder reordenarlas fácilmente en distintos puntos de ruptura.

Preparar WordPress

1) Registrar tamaños de imagen y añadir soporte

Registra tamaños específicos para que las imágenes encajen bien en las áreas del grid y aproveches srcset/width descriptors.

// funciones.php
add_theme_support( post-thumbnails )
add_image_size( mag-hero, 1600, 900, true )   // grande para hero
add_image_size( mag-large, 800, 600, true )
add_image_size( mag-medium, 600, 400, true )
add_image_size( mag-small, 400, 300, true )

2) Encolar estilos y scripts

Asegúrate de cargar una hoja específica de estilos para la portada tipo revista.

// funciones.php
function theme_enqueue_magazine_styles() {
  wp_enqueue_style( theme-magazine, get_theme_file_uri( /css/magazine.css ), array(), 1.0 )
}
add_action( wp_enqueue_scripts, theme_enqueue_magazine_styles )

Estructura de plantilla (HTML/PHP)

La plantilla puede ser home.php o una plantilla específica para la portada. Se mostrará un ejemplo simplificado con una consulta personalizada para seleccionar los posts destacados y el loop principal. El código incluido es orientativo adáptalo según tu estructura y funciones de tema.

lt?php
// home.php (fragmento)
// Consulta para posts destacados / hero
hero_query = new WP_Query( array( posts_per_page =gt 1, cat =gt 0 ) ) // ajustar según lógica
featured_query = new WP_Query( array( posts_per_page =gt 4, offset =gt 1 ) )
?gt

lt!-- Contenedor principal de la revista --gt
ltdiv class=mag-gridgt

  lt?php if ( hero_query-gthave_posts() ) : while( hero_query-gthave_posts() ) : hero_query-gtthe_post() ?gt
    ltarticle class=mag-item mag-item--herogt
      lta href=lt?php the_permalink() ?gt class=mag-linkgtlt?php the_post_thumbnail( mag-hero ) ?gtlt/agt
      lth2 class=mag-titlegtlta href=lt?php the_permalink() ?gtgtlt?php the_title() ?gtlt/agtlt/h2gt
    lt/articlegt
  lt?php endwhile wp_reset_postdata() endif ?gt

  lt?php if ( featured_query-gthave_posts() ) : i = 0 while( featured_query-gthave_posts() ) : featured_query-gtthe_post() i   ?gt
    ltarticle class=mag-item mag-item--feat mag-item--feat-gt
      lta href=lt?php the_permalink() ?gtgtlt?php the_post_thumbnail( mag-medium ) ?gtlt/agt
      lth3gtlta href=lt?php the_permalink() ?gtgtlt?php the_title() ?gtlt/agtlt/h3gt
    lt/articlegt
  lt?php endwhile wp_reset_postdata() endif ?gt

  lt!-- Loop principal para posts secundarios --gt
  ltsection class=mag-listgt
    lt?php if ( have_posts() ) : while ( have_posts() ) : the_post() ?gt
      ltarticle class=mag-item mag-item--listgt
        lta href=lt?php the_permalink() ?gtgtlt?php the_post_thumbnail( mag-small ) ?gtlt/agt
        lth4gtlta href=lt?php the_permalink() ?gtgtlt?php the_title() ?gtlt/agtlt/h4gt
      lt/articlegt
    lt?php endwhile endif ?gt
  lt/sectiongt

lt/divgt

CSS: crear las Grid Areas

A continuación tienes un CSS completo y comentado. Se usan nombres de áreas para la plantilla y se hacen media queries para móviles y tablet. Ajusta tamaños, gaps y colores al diseño de tu tema.

/ magazine.css /
.mag-grid {
  display: grid
  gap: 1rem
  grid-template-columns: repeat(12, 1fr)
  grid-template-rows: auto
  grid-template-areas:
    hero hero hero hero hero hero hero hero hero hero hero hero
    feat1 feat1 feat2 feat2 feat3 feat3 feat4 feat4 list list list list
    list list list list list list list list list list list list
  align-items: start
}

/ articulos /
.mag-item { background: #fff overflow: hidden }
.mag-item--hero { grid-area: hero }
.mag-item--feat-1 { grid-area: feat1 }
.mag-item--feat-2 { grid-area: feat2 }
.mag-item--feat-3 { grid-area: feat3 }
.mag-item--feat-4 { grid-area: feat4 }
.mag-list { grid-area: list display: grid grid-template-columns: repeat(3, 1fr) gap: 1rem }

/ Estilos generales dentro de items /
.mag-item img { width: 100% height: auto display: block }
.mag-title, .mag-item h3, .mag-item h4 { margin: .5rem 0 font-weight: 700 }

/ Responsive: tablet /
@media (max-width: 1024px) {
  .mag-grid {
    grid-template-columns: repeat(8, 1fr)
    grid-template-areas:
      hero hero hero hero hero hero hero hero
      feat1 feat1 feat2 feat2 feat3 feat3 feat4 feat4
      list list list list list list list list
  }
  .mag-list { grid-template-columns: repeat(2, 1fr) }
}

/ Responsive: móvil /
@media (max-width: 600px) {
  .mag-grid {
    grid-template-columns: 1fr
    grid-template-areas:
      hero
      feat1
      feat2
      feat3
      feat4
      list
  }
  .mag-list { grid-template-columns: 1fr }
}

/ Accesibilidad visual: foco en enlaces /
.mag-link:focus,
.mag-item a:focus {
  outline: 3px solid #005fcc
  outline-offset: 2px
}

Explicación clave del CSS

Optimización de imágenes y rendimiento

  1. Usa los tamaños personalizados (add_image_size) y llama a the_post_thumbnail con el tamaño requerido.
  2. Activa lazy-loading nativo (atributo loading=lazy en imágenes) o usa built-in de WordPress (WP 5.5 lo añade por defecto).
  3. Minifica y concatena CSS crítico: extrae el CSS crítico para el hero y primeros elementos y carga el resto asincrónicamente si es necesario.
  4. Evita consultas excesivas: limita posts por consulta y usa transients si el contenido no cambia cada segundo.

Accesibilidad y SEO

Fallbacks y compatibilidad

CSS Grid tiene soporte amplio, pero para navegadores antiguos puedes proporcionar un fallback simple con display: block o un grid basado en floats/flexbox. Un enfoque práctico es usar feature queries para aplicar Grid sólo si está soportado.

/ Fallback: aplica estilos básicos si no hay Grid /
@supports (display: grid) {
  / grid styles already definidos /
}
@supports not (display: grid) {
  .mag-grid { display: block }
  .mag-item { margin-bottom: 1rem }
  .mag-list { display: flex flex-wrap: wrap gap: 1rem }
  .mag-list .mag-item--list { flex: 1 1 calc(33.333% - 1rem) }
}

Checklist final antes de publicar

Errores comunes y soluciones rápidas

Recursos útiles

Conclusión

Un layout tipo revista con CSS Grid areas ofrece flexibilidad y control visual sin ensuciar el HTML. Separar la semántica (PHP/HTML) del diseño (CSS Grid) facilita futuras reordenaciones y pruebas A/B. Implementa tamaños de imagen adecuados, optimiza la carga y usa media queries para ofrecer una experiencia excelente en todas las pantallas.



Leave a Reply

Your email address will not be published. Required fields are marked *