Cuando construyes temas WordPress personalizados, a menudo necesitas mostrar no solo la categoría actual, sino también su categoría padre (para navegación de migas de pan o menús jerarquicos).
Descubre más sobre desarrollo profesional WordPress en WPPoland.
WordPress almacena las categorías en una estructura jerarquica, pero get_the_category() devuelve un array plano. Aqui te mostramos como extraer la jerarquía.
Método: get_the_category() + comprobacion de padre
Aqui tienes una función lista para pegar en functions.php:
function wppoland_get_category_hierarchy() {
$categories = get_the_category();
if ( empty( $categories ) ) {
return false;
}
// Obtener la primera categoria
$category = $categories[0];
$output = '';
// Si la categoria tiene padre
if ( $category->parent ) {
$parent = get_category( $category->parent );
$output .= '<a href="' . esc_url( get_category_link( $parent->term_id ) ) . '">' . esc_html( $parent->name ) . '</a> » ';
}
// Categoria actual
$output .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '">' . esc_html( $category->name ) . '</a>';
return $output;
}
Uso en la plantilla
<?php
$hierarchy = wppoland_get_category_hierarchy();
if ( $hierarchy ) {
echo '<div class="category-breadcrumb">' . $hierarchy . '</div>';
}
?>
Esto mostrara algo como: Tecnologia >> WordPress
Alternativa: Rastro completo de migas de pan
Si necesitas la jerarquía completa (abuelo, padre, hijo), usa este enfoque recursivo:
function wppoland_get_full_category_trail( $category_id ) {
$trail = array();
while ( $category_id ) {
$category = get_category( $category_id );
array_unshift( $trail, $category );
$category_id = $category->parent;
}
$output = '';
foreach ( $trail as $cat ) {
$output .= '<a href="' . esc_url( get_category_link( $cat->term_id ) ) . '">' . esc_html( $cat->name ) . '</a> » ';
}
return rtrim( $output, ' » ' );
}
Seleccion de la categoría primaria
Cuando una entrada tiene multiples categorías, necesitas determinar cual es la “primaria”. Varios plugins SEO ofrecen esta funcionalidad:
Con Yoast SEO
function wppoland_get_primary_category() {
$post_id = get_the_ID();
// Comprobar si Yoast tiene una categoria primaria definida
if ( class_exists( 'WPSEO_Primary_Term' ) ) {
$primary_term = new WPSEO_Primary_Term( 'category', $post_id );
$primary_cat_id = $primary_term->get_primary_term();
if ( $primary_cat_id ) {
return get_category( $primary_cat_id );
}
}
// Fallback: primera categoria
$categories = get_the_category( $post_id );
return ! empty( $categories ) ? $categories[0] : null;
}
Con RankMath
function wppoland_get_rankmath_primary_category() {
$post_id = get_the_ID();
// RankMath almacena la categoria primaria en post meta
$primary_cat_id = get_post_meta( $post_id, 'rank_math_primary_category', true );
if ( $primary_cat_id ) {
return get_category( $primary_cat_id );
}
// Fallback
$categories = get_the_category( $post_id );
return ! empty( $categories ) ? $categories[0] : null;
}
Implementación con Schema.org BreadcrumbList
Para SEO, es importante marcar las migas de pan con datos estructurados:
function wppoland_schema_breadcrumbs() {
$categories = get_the_category();
if ( empty( $categories ) ) return;
$category = $categories[0];
$trail = array();
// Construir rastro de categorias
$current = $category;
while ( $current ) {
array_unshift( $trail, $current );
$current = $current->parent ? get_category( $current->parent ) : null;
}
// Generar JSON-LD
$items = array();
$position = 1;
// Inicio
$items[] = array(
'@type' => 'ListItem',
'position' => $position++,
'name' => 'Inicio',
'item' => home_url()
);
// Categorias
foreach ( $trail as $cat ) {
$items[] = array(
'@type' => 'ListItem',
'position' => $position++,
'name' => $cat->name,
'item' => get_category_link( $cat->term_id )
);
}
// Entrada actual
$items[] = array(
'@type' => 'ListItem',
'position' => $position,
'name' => get_the_title(),
'item' => get_permalink()
);
$schema = array(
'@context' => 'https://schema.org',
'@type' => 'BreadcrumbList',
'itemListElement' => $items
);
echo '<script type="application/ld+json">' . wp_json_encode( $schema ) . '</script>';
}
add_action( 'wp_head', 'wppoland_schema_breadcrumbs' );
Estilizacion CSS de las migas de pan
.category-breadcrumb {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.875rem;
color: #6b7280;
margin-bottom: 1rem;
}
.category-breadcrumb a {
color: #3b82f6;
text-decoration: none;
transition: color 0.2s ease;
}
.category-breadcrumb a:hover {
color: #1d4ed8;
text-decoration: underline;
}
/* Separador personalizado */
.category-breadcrumb span.separator {
color: #d1d5db;
font-size: 0.75rem;
}
/* Responsivo */
@media (max-width: 640px) {
.category-breadcrumb {
font-size: 0.75rem;
flex-wrap: wrap;
}
}
Migas de pan para taxonomías personalizadas
La misma lógica se aplica a taxonomías personalizadas. Solo necesitas reemplazar las funciones de categoría con las equivalentes de taxonomía:
function wppoland_get_custom_taxonomy_trail( $taxonomy, $post_id = null ) {
$post_id = $post_id ?: get_the_ID();
$terms = get_the_terms( $post_id, $taxonomy );
if ( ! $terms || is_wp_error( $terms ) ) {
return '';
}
// Tomar el primer termino
$term = $terms[0];
$trail = array();
// Construir jerarquia
$current = $term;
while ( $current ) {
array_unshift( $trail, $current );
$current = $current->parent ? get_term( $current->parent, $taxonomy ) : null;
}
$output = '';
foreach ( $trail as $t ) {
$link = get_term_link( $t, $taxonomy );
if ( ! is_wp_error( $link ) ) {
$output .= '<a href="' . esc_url( $link ) . '">' . esc_html( $t->name ) . '</a> » ';
}
}
return rtrim( $output, ' » ' );
}
Rendimiento y cache
Para sitios con alto tráfico, considera almacenar en cache el resultado de las migas de pan:
function wppoland_cached_breadcrumbs() {
$post_id = get_the_ID();
$cache_key = 'breadcrumbs_' . $post_id;
$output = get_transient( $cache_key );
if ( false === $output ) {
$output = wppoland_get_full_category_trail(
get_the_category()[0]->term_id ?? 0
);
set_transient( $cache_key, $output, DAY_IN_SECONDS );
}
return $output;
}
// Invalidar cache cuando se actualiza la entrada
add_action( 'save_post', function( $post_id ) {
delete_transient( 'breadcrumbs_' . $post_id );
});
Integración con Block Editor
En temas de bloques, puedes crear un bloque personalizado para migas de pan de categorías:
register_block_type( 'wppoland/category-breadcrumbs', [
'render_callback' => function() {
$hierarchy = wppoland_get_category_hierarchy();
if ( ! $hierarchy ) return '';
return sprintf(
'<nav class="wp-block-wppoland-breadcrumbs" aria-label="Migas de pan">%s</nav>',
$hierarchy
);
},
]);
Resumen
Esta solución es limpia, eficiente y maneja correctamente jerarquías de categorías de multiples niveles. Los puntos clave son:
- Usa
get_the_category()para obtener las categorías de la entrada - Recorre la propiedad
parentpara construir la jerarquía - Implementa Schema.org BreadcrumbList para SEO
- Considera la cache para sitios de alto tráfico
- Soporta tanto categorías nativas como taxonomías personalizadas


