I’ve actually been wanting to add breadcrumb navigation to my blog for a while now. It would not only benefit visitors browsing the blog but also be favorable for search engines. However, with so many things on my plate during the school term, many planned tasks never got done — I barely even updated the blog. Now that winter break is here, I should finally have plenty of time to tackle the things I’ve been wanting to do.
The concept of breadcrumb navigation comes from the fairy tale “Hansel and Gretel.” When Hansel and Gretel wandered through the forest and got lost, they discovered they had left a trail of breadcrumbs along the way, which helped them find their way home. Similarly, breadcrumb navigation tells visitors where they currently are on a website and how to navigate back.
The utility of breadcrumb navigation is immense — it lets users know their current position and where the current page sits within the overall site structure. But in my opinion, the greatest benefit of breadcrumbs is the ability to quickly return to the previous level, reducing unnecessary clicks and actions. After some deliberation, I couldn’t find the perfect spot to place the navigation, so I’ll just share the code I’ve put together for now.
Adding the Logic Code to function.php
First, edit your theme’s function.php and add the following code:
function get_breadcrumbs() {
global $wp_query;
if (!is_home()) {
// Start the UL
echo' < ul > ';
// Add the Home link
echo' < a href = "'.get_settings('home').'" > '.Home.' < /a>';
if ( is_category() )
{
$catTitle = single_cat_title( "", false );
$cat = get_cat_ID( $catTitle );
echo " » ". get_category_parents( $cat, TRUE, " » " ) ;
}
elseif ( is_archive() && !is_category() )
{
echo "» Archives";
}
elseif ( is_search() ) {
echo "» Search Results";
}
elseif ( is_404() )
{
echo "» 404 Not Found";
}
elseif ( is_single() )
{
$category = get_the_category();
$category_id = get_cat_ID( $category[0]->cat_name );
echo '» '. get_category_parents( $category_id, TRUE, " » " );
echo the_title('','', FALSE);
}
elseif ( is_page() )
{
$post = $wp_query->get_queried_object();
if ( $post->post_parent == 0 ){
echo "<li> » ".the_title('','', FALSE)."</li > ";
} else {
$title = the_title('', '', FALSE);
$ancestors = array_reverse(get_post_ancestors($post - >ID));
array_push($ancestors, $post - >ID);
foreach($ancestors as $ancestor) {
if ($ancestor != end($ancestors)) {
echo' < li > » < a href = "'.get_permalink($ancestor).'" > '.strip_tags(apply_filters('single_post_title', get_the_title($ancestor))).' < /a></li > ';
} else {
echo' < li > »'.strip_tags(apply_filters('single_post_title', get_the_title($ancestor))).' < /li>';
}
}
}
}
/ / End the UL echo" < /ul>";
}
}
Displaying the Breadcrumb Navigation
Once you’ve modified the function.php file, simply paste the following code wherever you want the navigation to appear.
if (function_exists('get_breadcrumbs')){
get_breadcrumbs();
}