Custom breadcrumb using Breadcrumb NavXT

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

Reader Interactions

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *