Blog

2016.09.25

Custom wordpress breadcrumbs multiple levels function without plugin

I was working on a project recently and found out that there is a little bit of a struggle to create breadcrumbs that will display page parent and all ancestors. Most tutorials out there are about two level breadcrumbs navigation.

Therefore I created a function for those who might happen to be in the same position. Simply add this function to your functions.php file and after that call it where you need it.

function streamlineBreadcrumbs($post, $displayCurrent){
	$count = 1;
	$postAncestors = get_post_ancestors($post);
	$sortedAncestorArray = array();
	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>";
		$count++;
	}
	if($displayCurrent){ //If TRUE - output the current page title
		echo "<span>". get_the_title($post) ."</span>";
	}
}

After you have added this to your functions.php, go to your template and place this function where you would want to display the breadcrumbs with multiple levels:

<?php streamlineBreadcrumbs($post,true); ?>

If you don’t want to display the current page title, then change the second value from true to false.

After this you should see a row with current page parent and all of its ancestors – now go ahead and style the breadcrumbs row using CSS as you need.

In categories: Tutorials, Website development, Wordpress

Nauris Kolāts

Nauris is a freelance designer / developer who loves to dig into the UX as much as in the ground for fishing worms. And fishing is just one amongst the long list of his active lifestyle hobbies.

Other posts

Your thoughts

Latest work