Craig Simpson

Web developer from Moray, Scotland

Custom breadcrumb using Breadcrumb NavXT

15th March 2018

3 Comments

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.

1add_action( 'bcn_after_fill', 'project_rebuild_breadcrumb' );
2/**
3 * Rebuild the breadcrumb created by Breadcrumb NavXT.
4 *
5 * @param bcn_breadcrumb_trail $breadcrumb Instance of the currently active breadcrumb trail.
6 */
7function project_rebuild_breadcrumbs( $breadcrumb ) {
8 
9 if ( ! is_singular( [ 'case-studies', 'articles', 'presentations', 'papers-reports', 'creative-portfolio' ] ) ) {
10 return;
11 }
12 
13 // Default breadcrumb template.
14 $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>';
15 
16 /**
17 * Store the first and last breadcrumbs, we're rebuilding the middle part.
18 */
19 $breadcrumb_root = reset( $breadcrumb->breadcrumbs );
20 $breadcrumb_end = end( $breadcrumb->breadcrumbs );
21 
22 /**
23 * Build our custom Knowledge breadcrumb.
24 */
25 $knowledge_page = get_page_by_path( 'knowledge' );
26 $breadcrumb_title = __( 'Knowledge', 'project' );
27 $breadcrumb_link = get_the_permalink( $knowledge_page->ID );
28 $knowledge_item_breadcrumb = new bcn_breadcrumb( $breadcrumb_title, $breadcrumb_template, [], $breadcrumb_link, $knowledge_page->ID );
29 
30 /**
31 * Update the Breadcrumb NavXT object.
32 */
33 $breadcrumb->breadcrumbs = [
34 $breadcrumb_root,
35 $knowledge_item_breadcrumb,
36 $breadcrumb_end,
37 ];
38}
39}

3 comments

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

  2. Paul says:

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

  3. Kris McGill says:

    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 to Paulie Webster Cancel reply

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