SarahCreate a Breadcrumb Trail

Written by Sarah from Stuff By Sarah

Adding a breadcrumb trail to your WordPress site is fairly easy to do. Yes, before anyone mentions it, there are plugins out there to do this for you, but you won’t learn from those unless you actually open them up and change things. So for those of you who actually want to learn how you can easily extend the functionality of WordPress (or for those who just want to copy the final code..!) read on ;)

This week I’m going to explain how to add in a new function to our functions.php theme file, to allow you to create a breadcrumb trail for your front page, posts and pages. For our front page we just want to show the home link (you may want to show nothing at all which is also fine). For our static Pages we want to show the page and any parent pages, and the home link, and for the posts we want the home link and the categories and parent categories (note this method only works with one category, so if you put posts in multiple categories you’ll only get the first one showing in the breadcrumb trail).

The Opening Code

So we just need to construct this step by step. The basic function will begin as:

function write_breadcrumb() {
	$pid = $post->ID;
	$trail = "<a href='/'>Home</a>";

        return $trail;
}

We then call this by adding

<p>< ?php echo write_breadcrumb(); ?></p>

This would give us an ordered list with one list item of the home link (note you may need to change your home link if WordPress is installed within a directory on your site).

Next we start checking which page is calling the function, so first let’s check if it’s the front page by using the is_front_page() condition (this will then work for both blogs and CMS sites with a static front page). eg.

function write_breadcrumb($pid = 0) {
	$trail = "<a href='/'>Home</a>";

	if (is_front_page()) :
		// do nothing
	endif;

        return $trail;
}

As mentioned, all we need is the Home link on the front page. In theory we could remove this by simply changing the $trail variable to be a non breaking space ( ).

Static Pages

The next job is to get it to work for static pages. This is where the $pid variable comes in, because we can get the post ID in the function using the $post->ID value (note, the breadcrumb trail needs to be within the WordPress loop to work). We then take this ID and get the page name for it. Then we also check to see if it has a parent, if it does we get the details for that, again we check if that has a parent, and continue until the parent page is at the top of the tree ie.

if (is_page()) :
	$bcarray = array();
	$pdata = get_post($pid);
	$bcarray[] = " &raquo; ".$pdata->post_title;
	while ($pdata->post_parent) :
		$pdata = get_post($pdata->post_parent);
		$bcarray[] = " &raquo; <a href='".get_permalink($pdata->ID)."'>".$pdata->post_title."</a>\n";
	endwhile;
endif;

So in the above we use the get_post function to get the details of the page using its ID. The page we’re on is not linked as there’s no real point in linking the page you’re currently on. Then we check to see if there is a parent ID for this page, which is done in the while loop. We repeat the process within the loop then, get the data for the post, create a link to the parent page and then loop again to see if the parent page has a parent itself.

So if the page had no parent, then the post_parent would be 0 and the while loop wouldn’t execute, if it was just a child page, then the while loop would execute once and then stop, so this way we can check for all parent and grandparent pages.

The results are saved into an array, this is because we’re getting them in reverse order, so we need to store them in an array and then once we’re finished, we reverse the array results using array_reverse. So after our endwhile we reverse the array and then run through each result and add it to our original $trail variable ie.

$bcarray = array_reverse($bcarray);
foreach ($bcarray AS $listitem) :
	$trail .= $listitem;
endforeach;

Single Posts

For the single posts we want to display the category and parent categories in the breadcrumb trail. You could also store the post title however with long post titles, this may create quite a long breadcrumb trail. So I’ve omitted the post title from the trail. Luckily WordPress gives us a function to get the category and it’s parents so we don’t need to do anything as complex as above. This is done in a few lines of code:

if (is_single()) :
	$pdata = get_the_category($pid);
	$data = get_category_parents($pdata[0]->cat_ID, TRUE, ' &raquo; ');

	$trail .= " &raquo; ".substr($data,0,-8);
endif;

The first line uses the get_the_category() function to get the category details. From this we can get the category ID. Then the get_category_parents() function takes the category ID and generates a list of the category links. We then just append this to the $trail variable, however we need to add an opening list item to the $data variable, as it’s missing, and we need to remove the additional right angled quote from the end of the $data string, so a simple substr() works fine for this.

Final Code

So the final code so far gives us:

function write_breadcrumb() {
	$pid = $post->ID;
	$trail = "<a href='/'>Home</a>";

	if (is_front_page()) :
		// do nothing
	elseif (is_page()) :
		$bcarray = array();
		$pdata = get_post($pid);
		$bcarray[] = " &raquo; ".$pdata->post_title."\n";
		while ($pdata->post_parent) :
			$pdata = get_post($pdata->post_parent);
			$bcarray[] = " &raquo; <a href='".get_permalink($pdata->ID)."'>".$pdata->post_title."</a>\n";
		endwhile;
		$bcarray = array_reverse($bcarray);
		foreach ($bcarray AS $listitem) :
			$trail .= $listitem;
		endforeach;
	elseif (is_single()) :
		$pdata = get_the_category($pid);
		$data = get_category_parents($pdata[0]->cat_ID, TRUE, ' &raquo; ');

		$trail .= " &raquo; ".substr($data,0,-8);
	endif;

	return $trail;
}

And then to use this on the front page you can just call it as

<p>< ?php echo write_breadcrumb(); ?></p>

And this can be called anywhere on the front page. For the static Pages and single posts we need to put this within the loop.

Next week I’ll then explain how we can extend this to work for the category and archive pages.

Follow this blogger on Twitter!

  • Digg This Post
  • Tweet This Post
  • Stumble This Post
  • Submit This Post To Delicious
  • Submit This Post To Reddit
  • Submit This Post To Mixx

17 Responses to “Create a Breadcrumb Trail”

Author comments are in a darker gray color for you to easily identify the posts author in the comments

  1. This is a really great writeup of WordPress Breadcrumbs. I have a couple of suggestions for improvements though if I may.

    If you have WordPress installed in a subdirectory, the Home link might not take you where you'd expect. I would suggest replacing line 3 with the following:

    <code>$trail = 'Home';</code>

    This will ALWAYS take you to the WordPress home page.

    Also, rather than hard coding the & raquo; It would probably be better to assign it to a variable at the beginning and then use the variable throughout the rest of the function. That way if you decide to use another character as a separator you only have to change one line.

  2. Sorry, the code didn't work out as expected. Here it is properly escaped.

    <code>$trail = 'Home</code>

  3. Sarah says:

    Hi Will, yeah the getbloginfo() will work, but it will save on an extra db call by just hardcoding it in. Of course either is fine and probably unnoticeable unless your site is very busy. For the rightangled quote, to be honest the best method is to use a list (which I'll be uploading in a file as a different method next week). I had this originally, unfortunately WordPress broke half my code so the addition of a right angled quote was a last minute thing!

  4. You have a good point with the extra db call. Since this is presumably going in functions.php I guess hard coding the URL wouldn't be the end of the world.

  5. Roger says:

    Thanks for this post – tried it out and got my breadcrumb working perfectly! Did a few tweaks here and there and I'm so pleased with the result. Really am glad I stumbled upon this post.

  6. Wow, excellent documentation on the process. Most people I know that are set up on Wordpress are strictly using pre-built themes and plugins since they're not technically apt. Great resource for the custom developer or newbie tweaker. :)

  7. Ken the tech says:

    Thanks! You give me the idea of breadcrumb and of course the solution. Nice tutorial :)

  8. YoU says:

    Love the tutorial!

    PS. I'm not a coder, is there any way to add post title after the category name? You omit this part because of it may create a long breadcrumb trail.

  9. Sarah says:

    Sure, to add the post title at the end, on line 23 of the final code above, remove the substr() line (just remove the whole line), and replace it with

    <code>$pdata = get_post($pid);

    $trail .= "<a href='".get_permalink($pid)."'>".$pdata->post_title."
    "; </code>

    and that should do what you need :)

  10. YoU says:

    Thank you very much Sarah! It works like a charm!

    I added the code just after the line 23 (instead of remove it) and it showed the post title after the category name.

    I implement the style to make it like an apple.com one, you can have a look at it on my test bed (at the bottom).

  11. ElShaddai Edwards says:

    Thank you for this post – I am looking forward to digging into the code!

    I am currently working with your Page Menu Editor plugin and have alternate (less verbose) page titles defined for my nav menus – will the breadcrumb function above use the alternate titles as defined in your plugin, or will it use the default WP page titles? If the latter, is there any way to use the alternate titles in a breadcrumb?

  12. Sarah says:

    To specifically get the menu labels from my page menu editor you would use the following to access the specific page menu label:

    <code>get_post_meta($pid, 'menulabel', true)</code>

    So on the final code above you could replace line 10 with

    <code>$bcarray[] = " » ".get_post_meta($pid, 'menulabel', true)."
    ";</code>

  13. Miklas says:

    Is there a way to get the breadcrumb in reverse order? So it reads "posttitle <- subcategory <- category <- home"</b> instead of the usual left to right?

Trackbacks

  1. [...] the full post – Create a Breadcrumb Trail on [...]

  2. [...] Create a Breadcrumb Trail – Written by Sarah from Stuff By Sarah Adding a breadcrumb trail to your WordPress site is fairly easy to do. Yes, before anyone mentions it, … [...]

  3. [...] week I wrote about creating a breadcrumb trail, explaining how to do this for your front page, static Page and single post page. This leaves us [...]

  4. [...] week I wrote about creating a breadcrumb trail, explaining how to do this for your front page, static Page and single post page. This leaves us [...]

Comments are closed.

Comments are closed since this post is older than 30 days. However, you can continue this discussion in our popular Blogging Forums

Subscribe To BloggingTips Via RSS Subscribe To Blogging Tips Via Email Follow Us On Twitter Follow us on Facebook Find Out More About Our Newsletter

Sponsors

Blogging Tips Newsletter

Six Figure Blogging

 

Our Free E-Books