A template function that prints accessible breadcrumbs for posts, pages, archives, search and 404 pages.
/**
* Usage in a template: nahnu_breadcrumbs();
*/
function nahnu_breadcrumbs(): void {
if ( is_front_page() ) {
return;
}
$items = [ [ 'Home', home_url( '/' ) ] ];
if ( is_singular( 'post' ) ) {
$cats = get_the_category();
if ( $cats ) {
$items[] = [ $cats[0]->name, get_category_link( $cats[0] ) ];
}
} elseif ( is_page() ) {
foreach ( array_reverse( get_post_ancestors( get_the_ID() ) ) as $ancestor ) {
$items[] = [ get_the_title( $ancestor ), get_permalink( $ancestor ) ];
}
}
if ( is_singular() ) {
$items[] = [ get_the_title(), '' ];
} elseif ( is_category() || is_tag() || is_tax() ) {
$items[] = [ single_term_title( '', false ), '' ];
} elseif ( is_search() ) {
$items[] = [ sprintf( 'Search results for "%s"', get_search_query( false ) ), '' ];
} elseif ( is_404() ) {
$items[] = [ 'Page not found', '' ];
} elseif ( is_archive() ) {
$items[] = [ wp_strip_all_tags( get_the_archive_title() ), '' ];
}
echo '<nav class="nahnu-breadcrumbs" aria-label="Breadcrumb"><ol>';
$last = array_key_last( $items );
foreach ( $items as $i => [ $label, $url ] ) {
echo '<li>';
if ( $url && $i !== $last ) {
echo '<a href="' . esc_url( $url ) . '">' . esc_html( $label ) . '</a>';
} else {
echo '<span aria-current="page">' . esc_html( $label ) . '</span>';
}
echo '</li>';
}
echo '</ol></nav>';
}
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
Breadcrumbs show visitors where they are and give them a quick way back up. This function prints them for any kind of page, ready to drop into a theme template.
The function starts with Home, then adds the post’s first category for blog posts, or every parent page for nested pages. The last item is the current page’s title, the term name, the search phrase, “Page not found” or the archive title.
The markup follows accessibility guidance: a <nav> labelled “Breadcrumb”, an ordered list and aria-current="page" on the last item, which isn’t a link.
nahnu_breadcrumbs(); where you want them, for example in a child theme’s single.php, or with a Code element in a page builder..nahnu-breadcrumbs ol with display:flex; list-style:none; gap:8px and add separators with li + li::before.Call the function in a template and open a nested page. You should see Home / Parent / Current page.