WordPress Breadcrumbs

By: Ryan Kienstra on: October 14, 2014  in: Programming

Breadcrumb IconBreadcrumbs at the top of the page help readers see where they are, and where they can go.

One problem is that functions that automatically echo breadcrumbs make a link for each of the pages. But some pages are only placeholders.

For example, if you try to click “Plugins” at the top of this page, there is no link. It only serves to list its menu items.

So you wouldn’t want a link to this in the breadcrumbs.

I created these functions to show breadcrumbs without the link to empty pages. These are in my theme’s functions.php file. I call awp_the_breadcrumbs() in my theme before the content-page.php template.

The function awp_echo_breadcrumbs uses Bootstrap markup, but you could change it.

function awp_the_breadcrumbs() {
  global $post ;
  if ( ! isset( $post ) ) {
    return ;
  }
  else if ( awp_current_post_has_parent() ) {
    awp_echo_breadcrumbs() ;
  }
}

function awp_current_post_has_parent() {
  global $post ;
  $parent_title = get_the_title( $post->post_parent ) ;
  return ( $parent_title != the_title( "" , "" , false ) ) ;
}

function awp_echo_breadcrumbs() {
  global $post ;
  ?>
    <ol class="breadcrumb">
      <li><a href="<?php echo home_url() ; ?>">Home</a></li>
      <li><?php awp_echo_post_parent_for_breadcrumb() ; ?></li>
      <li class="active"><?php the_title() ; ?></li>
    </ol>
  <?php
}

function awp_echo_post_parent_for_breadcrumb() {
  global $post ;
  $post_parent = get_post( $post->post_parent ) ;

  if ( awp_post_is_only_a_placeholder_and_has_no_content( $post_parent ) ) {
    echo get_the_title( $post_parent ) ;
  } else {
    awp_echo_post_title_wrapped_in_a_link( $post_parent ) ;
  }
}

function awp_post_is_only_a_placeholder_and_has_no_content( $post_parent ) {
  return ( "" == $post_parent->post_content ) ;
}

function awp_echo_post_title_wrapped_in_a_link( $post_parent ) {
  $parent_title = get_the_title( $post_parent ) ;
  $parent_link = get_permalink( $post_parent ) ;
  echo "<a href='{$parent_link}' title='{$parent_title}'>{$parent_title}</a>\n" ;
}

In my theme, I wrap some of these functions in if ( ! function_exists( 'my_function_name' ) ) to make them pluggable.

The result is:

Breadcrumb at top of website


Leave a comment