Skip to content

Early-bird lifetime licence: $199 once, for the first 200 buyers only. See the offer

Breadcrumbs shortcode

Type [breadcrumbs] where you want a trail like Home › Recipes › Lemon cake. Works for posts, pages (with parents), categories and search.

  • Type PHP
  • Runs Where you put the [breadcrumbs] shortcode
  • Category Shortcodes
  • Tested with WordPress 7.1
PHP
<?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.

Move your snippets over this afternoon.

Importing changes nothing until you switch over, and your old shortcodes keep working.