Recently we made a site that needed breadcrumbs but was used as an internal portal. This means it didn’t need any SEO stuff so the standard Yoast breadcrumbs we use seemed like overkill.
Decided to create a couple simple functions to display our breadcrumbs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
/** * Get an array of all this posts ancestors * * @param object $post The post you would like to get the ancestors of * @param bool $home Would you like to get the home page as well? */ function jb_get_ancestors($post = '', $home = false ){ if(empty($post)){ global $post; } //get our current post and current parent $current_post = $post; $post_parent = $post->post_parent; //Collect all our crumbs $crumbs = array($post); //just in case we try to break things with an infinite loop, lets stop ourselves $safety = 10; while($post_parent > 0 && $safety > 0){ //get this parent post $current_post = get_post($current_post->post_parent); //update our current parent $post_parent = $current_post->post_parent; //add this new parent to the front of the array. Might be more efficient to just build the array and reverse? array_unshift($crumbs, $current_post); $safety--; } //if they want the home page as well stick that at the front of the array if($home){ array_unshift($crumbs, get_post(1)); } return $crumbs; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
/** * Create a trail of breadcrumbs * * @param string $sep The element you would like to use to separate your crumbs * @param bool $home Would you like display the homepage? * @param bool $echo Would you like to echo this immidiately? */ function jb_breadcrumbs($sep = '›', $home = false, $echo = true) { //add spaces around our separator $sep = ' '.$sep.' '; //Collect all our crumbs $crumbs = jb_get_ancestors('', $home); //build the crumb string $crumb_string = '<div class="breadcrumbs">'; foreach($crumbs as $ckey => $crumb){ //if($crumb->ID === 0) continue; $crumb_string .= '<a href="'.get_the_permalink($crumb->ID).'">'.$crumb->post_title.'</a>'.($ckey < count($crumbs) - 1?$sep:''); } $crumb_string .= '</div>'; //how does the user want this returned? if($echo){ echo $crumb_string; }else{ return $crumb_string; } } |
By sticking those two functions in your functions.php file and then calling jb_breadcrumbs() wherever you want to display these breadcrumbs you should be all set.