Categories

Bootstrap Breadcrumbs with PHP

by adesignguy Posted on 12/02/2016 20:37:48 | Category: Code

I found this excellent but not perfect function on stackoverflow and modified it as it allowed the last crumb to be a hyperlink and clickable, which is not right for the end user and just not semantically correct through the eyes of a web developer, so I added logic to find the last crumb in the foreach loop to display a non clickable last breadcrumb. I removed the custom text argument which allowed for a custom string such as "You are here". It's just clutter and bad design and really not needed.

I also added the bootstrap classes to the function as seen on this website(page).

PS: The html is easily adaptable for any other CSS framework too, just modify the html within the function.

All you need to do is add <?php echo breadcrumbs(); ?> to the very top of your page(s), below your top navigation area and add the below function to your PHP file or includes file.

Obviously if you are using bootstrap, you do not need to change the separator argument, leave as is, as the bootstrap css automatically adds them.

<?php

function breadcrumbs($sep = '', $home = 'Home') {
$bc     =   '<ul class="breadcrumb">';
//Get the server http address
$site   =   'http://'.$_SERVER['HTTP_HOST'];
//Get all vars en skip the empty ones
$crumbs =   array_filter( explode("/",$_SERVER["REQUEST_URI"]) );
//Create the homepage breadcrumb
$bc    .=   '<li><a href="'.$site.'">'.$home.'</a>'.$sep.'</li>';
//Count all not empty breadcrumbs
$nm     =   count($crumbs);
$i      =   1;
//Loop through the crumbs
foreach($crumbs as $crumb){
//grab the last crumb
$last_piece = end($crumbs);

    //Make the link look nice
    $link    =  ucfirst( str_replace( array(".php","-","_"), array(""," "," ") ,$crumb) );
       
    //Loose the last seperator
    $sep     =  $i==$nm?'':$sep;
    //Add crumbs to the root
    $site   .=  '/'.$crumb;
    //Check if last crumb
    if ($last_piece!==$crumb){
    //Make the next crumb
    $bc     .= '<li><a href="'.$site.'">'.$link.'</a>'.$sep.'</li>';
    } else {
    //Last crumb, do not make it a link
    $bc     .= '<li class="active">'.ucfirst( str_replace( array(".php","-","_"), array(""," "," ") ,$last_piece)).'</li>';
    }
    $i++;
}
$bc .=  '</ul>';
//Return the result
return $bc;
}
?>