Custom breadcrumb using Breadcrumb NavXT

Learn more about using the actions and filters built into Breadcrumb NavXT to modify your breadcrumb trail.

Recently I was asked to implement a custom breadcrumb trail for all posts in 5 different custom post types on a site using the Breadcrumb NavXT plugin. The posts belonged to different categories, were in different post types and all suffered from a messy breadcrumb trail. It was desired that all of the posts had a consistent breadcrumb trail, which was:

Home > Knowledge > {{ Post Name }}

Breadcrumb NavXT has an action which runs just after the breadcrumb trail has been built, and I was able to use it to rewrite the breadrcrumb trail to suit my requirements.

<?php
add_action( 'bcn_after_fill', 'project_rebuild_breadcrumb' );
/**
* Rebuild the breadcrumb created by Breadcrumb NavXT.
*
* @param bcn_breadcrumb_trail $breadcrumb Instance of the currently active breadcrumb trail.
*/
function project_rebuild_breadcrumbs( $breadcrumb ) {
if ( ! is_singular( [ 'case-studies', 'articles', 'presentations', 'papers-reports', 'creative-portfolio' ] ) ) {
return;
}
// Default breadcrumb template.
$breadcrumb_template = '<span class="breadcrumb-link-wrap" itemprop="itemListElement" itemscope="" itemtype="https://schema.org/ListItem" property="itemListElement" typeof="ListItem"><a itemprop="item" property="item" typeof="WebPage" title="Go to %title%." href="%link%" class="%type%"><span property="name">%htitle%</span></a><meta property="position" content="%position%"></span>';
/**
* Store the first and last breadcrumbs, we're rebuilding the middle part.
*/
$breadcrumb_root = reset( $breadcrumb->breadcrumbs );
$breadcrumb_end = end( $breadcrumb->breadcrumbs );
/**
* Build our custom Knowledge breadcrumb.
*/
$knowledge_page = get_page_by_path( 'knowledge' );
$breadcrumb_title = __( 'Knowledge', 'project' );
$breadcrumb_link = get_the_permalink( $knowledge_page->ID );
$knowledge_item_breadcrumb = new bcn_breadcrumb( $breadcrumb_title, $breadcrumb_template, [], $breadcrumb_link, $knowledge_page->ID );
/**
* Update the Breadcrumb NavXT object.
*/
$breadcrumb->breadcrumbs = [
$breadcrumb_root,
$knowledge_item_breadcrumb,
$breadcrumb_end,
];
}
}
view raw functions.php hosted with ❤ by GitHub

3 Comments

Paulie Webster 4th April 2018 Reply

Was able to use this to make my own custom breadcrumb, thank you so much!

Paul 17th February 2019 Reply

This was a huge help to me. Thanks for sharing it!

Kris McGill 24th November 2021 Reply

This was indeed very very helpful for adding custom breadcrumb titles to current breadcrumbs. I also tried adding custom breadcrumb to only a few pages using code here https://wordpress.org/support/topic/insert-item-between-breadcrumb-on-specific-pages/

Thank you.

Leave a Reply