Breadcrumbs shortcode
Type [breadcrumbs] where you want a trail like Home › Recipes › Lemon cake. Works for posts, pages (with parents), categories and search.
<?php
// [breadcrumbs]
$items = array( array( home_url( '/' ), __( 'Home' ) ) );
if ( is_singular() ) {
$post = get_queried_object();
if ( 'post' === $post->post_type ) {
$cats = get_the_category( $post->ID );
if ( $cats ) {
$items[] = array( get_category_link( $cats[0] ), $cats[0]->name );
}
}
foreach ( array_reverse( get_post_ancestors( $post ) ) as $parent ) {
$items[] = array( get_permalink( $parent ), get_the_title( $parent ) );
}
$items[] = array( '', get_the_title( $post ) );
} elseif ( is_category() || is_tag() || is_tax() ) {
$items[] = array( '', single_term_title( '', false ) );
} elseif ( is_search() ) {
/* translators: %s: search query. */
$items[] = array( '', sprintf( __( 'Search Results for: %s' ), get_search_query( false ) ) );
} elseif ( is_archive() ) {
$items[] = array( '', wp_strip_all_tags( get_the_archive_title() ) );
}
$out = array();
foreach ( $items as $item ) {
$out[] = $item[0] ? '<a href="' . esc_url( $item[0] ) . '">' . esc_html( $item[1] ) . '</a>' : '<span aria-current="page">' . esc_html( $item[1] ) . '</span>';
}
return '<nav class="breadcrumbs" aria-label="Breadcrumb">' . implode( ' <span aria-hidden="true">›</span> ', $out ) . '</nav>';
How to use it
Type [breadcrumbs] in a post, a page or a Shortcode block.
In these packs
- Shortcodes: Handy shortcodes for dates, breadcrumbs, buttons, share links, members-only content and more.