Here’s a simple script to generate breadcrumbs for any page or custom post type that uses parent pages to establish hierarchy. I’ve opted to only show breadcrumbs on pages that have at least one parent. If your page doesn’t have a parent, nothing will show up.
To get started, paste this function into functions.php:
function easy_breadcrumbs($post) { $parent_id = $post->post_parent; if ($parent_id == 0) { return false; } else { $output = ''; while ($parent_id != 0) { $ancestor = get_post($parent_id); $output = '<li><a href="'.get_permalink($ancestor->ID).'">'.$ancestor->post_title.'</a></li>' . $output; $parent_id = $ancestor->post_parent; } return '<ul class="breadcrumbs"><li><a href="'.home_url().'">Home</a></li>'.$output.'</ul>'; } }
To display the breadcrumbs, paste the following code into your template inside of the loop:
<?php echo easy_breadcrumbs($post); ?>
Now you have an unordered list. To make it look like you’d expect, you’ll need a little css. Something like this should do the trick:
.breadcrumbs { padding: 0; margin: 0; } .breadcrumbs li { display: inline-block; list-style: none; } .breadcrumbs li + li:before { content: ">"; display: inline-block; margin: 0 .4em 0 .2em; }
The permalinks were not working for me (it was using the parent permalink for all the ancestors) but changing get_permalink($ancestor->post_id) to get_permalink($ancestor->ID) fixed it.
Oops! Good catch. I’ve updated the original. Thanks!
sorry double post >.<
nice piece of code though, thanks! 😀