Display WordPress Breadcrumbs Without Using A Plugin
1. Add the <nav> code below to your template where you would like the breadcrumbs to be displayed.
<nav class="breadcrumbs">
<?php breadcrumbs($post,true); ?>
</nav>
2. Edit the following code as needed and add it to your theme's function.php file.
function breadcrumbs($post, $displayCurrent){
// Adds the Home page to the Breadcrumbs. Delete this line if you don't want to include the Home page.
echo '<a href="/">Home</a> <span class="fa fa-angle-right"> </span> ';
$count = 1;
$postAncestors = get_post_ancestors($post);
$sortedAncestorArray = array();
$categories = get_categories();
foreach ($postAncestors as $ancestor){
$sortedAncestorArray[] = $ancestor;
}
krsort($sortedAncestorArray); // Sort an array by key in reverse order
foreach ($sortedAncestorArray as $ancestor){
echo "<a class='breadcrumb-link-". $count ."' href='". esc_url(get_permalink($ancestor)) ."' title='". get_the_title($ancestor) ."'>". get_the_title($ancestor) ."</a>";
echo ' <span class="fa fa-angle-right"> </span> ';
$count++;
}
// Adds a link to the Shop page before listing the individual product.
if (is_product()) {
echo '<a href="/shop">Shop</a> <span class="fa fa-angle-right"> </span>';
}
// Displays the name of the category that the blog post is in before the blog post title. It will look like this Home > Category Name > Title of Blog Post.
if (in_category('category-name') &&! is_author() &&! is_category() &&! is_search()) {
echo '<a href="/category/category-name/">Category Name</a> <span class="fa fa-angle-right"> </span>';
}
// Displays the Shop link on the Cart page. It will look like Home > Shop > Cart.
if (is_cart()) {
echo '<a href="/shop">Shop</a> <span class="fa fa-angle-right"> </span>';
}
// Displays the Shop link followed by the Cart link on the Checkout page. It will look like Home > Shop > Cart > Checkout.
if (is_checkout()) {
echo '<a href="/shop">Shop</a> <span class="fa fa-angle-right"> </span> <a href="/cart">Cart</a> <span class="fa fa-angle-right"> </span>';
}
// Displays 'Search results for' followed by the search query for search results.
if (is_search()) {
echo 'Search results for "'. get_search_query().'"';
}
//If TRUE it outputs the current page's title without a link.
if($displayCurrent){
echo '<span>';
echo '' . wp_title( '', true, 'right' ) . '';
echo '</span>';
}
}
add_filter( 'woocommerce_enqueue_styles', '__return_false' );
Note: This code uses Font Awesome to display symbols. I'm using <span class="fa fa-angle-right"> </span> as separator between breadcrumb menu items. It displays a stylized version of the greater than symbol.
THANKS FOR READING
Thank you for reading Display WordPress Breadcrumbs Without Using A Plugin. I hope you enjoyed it. You can give me feedback, say hi or yell at me on twitter.com/beuinteractive.