Breadcrumbs Shortcode
Adds a [wpide_breadcrumbs] shortcode that prints Home > Category > Post style breadcrumbs with schema.org markup, for themes that do not have them.
Opens WPIDE on
Code
add_shortcode( 'wpide_breadcrumbs', function () {
$crumbs = array( array( 'Home', home_url( '/' ) ) );
if ( is_singular() ) {
$post = get_queried_object();
if ( 'post' === $post->post_type ) {
$cats = get_the_category( $post->ID );
if ( $cats ) {
foreach ( array_reverse( get_ancestors( $cats[0]->term_id, 'category' ) ) as $ancestor ) {
$crumbs[] = array( get_cat_name( $ancestor ), get_category_link( $ancestor ) );
}
$crumbs[] = array( $cats[0]->name, get_category_link( $cats[0] ) );
}
} elseif ( is_post_type_hierarchical( $post->post_type ) ) {
foreach ( array_reverse( get_post_ancestors( $post ) ) as $ancestor ) {
$crumbs[] = array( get_the_title( $ancestor ), get_permalink( $ancestor ) );
}
} elseif ( get_post_type_archive_link( $post->post_type ) ) {
$crumbs[] = array( get_post_type_object( $post->post_type )->labels->name, get_post_type_archive_link( $post->post_type ) );
}
$crumbs[] = array( get_the_title( $post ), '' );
} elseif ( is_category() || is_tag() || is_tax() ) {
$crumbs[] = array( single_term_title( '', false ), '' );
} elseif ( is_search() ) {
$crumbs[] = array( 'Search results', '' );
} elseif ( is_404() ) {
$crumbs[] = array( 'Page not found', '' );
} elseif ( is_archive() ) {
$crumbs[] = array( wp_strip_all_tags( get_the_archive_title() ), '' );
}
$html = '<nav class="wpide-breadcrumbs" aria-label="Breadcrumb"><ol itemscope itemtype="https://schema.org/BreadcrumbList" style="display:flex;flex-wrap:wrap;gap:.4em;list-style:none;margin:0 0 1em;padding:0;font-size:.9em;">';
foreach ( $crumbs as $i => $crumb ) {
$html .= '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem">' . ( $i ? '<span aria-hidden="true">› </span>' : '' );
$html .= $crumb[1]
? '<a itemprop="item" href="' . esc_url( $crumb[1] ) . '"><span itemprop="name">' . esc_html( $crumb[0] ) . '</span></a>'
: '<span itemprop="name" aria-current="page">' . esc_html( $crumb[0] ) . '</span>';
$html .= '<meta itemprop="position" content="' . ( $i + 1 ) . '"></li>';
}
return $html . '</ol></nav>';
} );
Notes
Place it in a Shortcode block in your single post or page template. If an SEO plugin already outputs breadcrumb schema, use only one of them.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.