Wordpress-Code-is-Poetry

Fixing Custom Post breadcrumbs

When using a ready made theme such as one of the excellent Elegant Themes one is confronted to small issues of broken sections of the page templates when introducing custom post and getting them to display properly in the page templates

One such issue is the breadcrumbs link not working properly as a result of the custom taxonomies not being picked up properly by the core functions.  Here is some workaround for this.

In the case of the Elegant themes, you will find the breadcrumbs.php file in the includes/ directory.

So for example in the single post page template, the breadcrumbs are displayed using the following code.

...
//some code to display the authors link followed by
$category = get_the_category(); //returns the categories of this post
$catlink = get_category_link( $category[0]->cat_ID ); //gets the links for the first category
echo ('<a href="'.esc_url($catlink).'">'.esc_html($category[0]->cat_name).'</a> '.'<span class="raquo">&raquo;</span> '.get_the_title()); 
//displays the category in the breadcrumb

So we can include the following lines in order to ensure it works with our custom post

global $post; //we need to ensure we have access to the post object breadcrumbs are handled in its own template
...
switch ( get_post_type($post) ){ //switch on the post_type
  case 'my_custom_post_type': //
    $category = get_the_terms($post->ID, 'my_custom_taxonomy');
    $first_term = reset($category);
    $catlink = get_term_link( $first_term );
    echo (''.esc_html($first_term->name).' '.'» '.get_the_title());
    break;
  default: //default 'post'and below is the default code 
    $category = get_the_category();
    $catlink = get_category_link( $category[0]->cat_ID );
    echo (''.esc_html($category[0]->cat_name).' '.'» '.get_the_title());
    break;
}

Want to share your thoughts?

Leave a Reply

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