I'm makeing dynamic bredcrumbs based on current url i have. My problem is, that i can't figure out how to generate right link and attach it to word, because of foreach loop. My code is realy messy, so i whould realy need a help. Hope you guys can help!
Tnx
Here is my code:
<?php
$url = current_url();
$home = "www.homepage.com";
$sub_url = substr($url, strpos($url, $home));
$segments = explode("/", $url);
$parts = array_slice($segments, 3);
$count = count($parts);
$i = 0;
?>
//Don't show breadcrumb on home page
<?php if (current_url() !== base_url() && current_url() !== base_url() . "home") { ?>
<div class="breadcrumbs">
<a href="<?php echo base_url(); ?>"><div class="home">Home</div></a>
<div class="divider1"></div>
<?php
foreach ($parts as $row) {
$bread = ucfirst(str_replace("-", " ", str_replace("_", " ", $row)));
?>
<div class="level1" style="margin-left: -6px ;">
<a href="#"><?php echo $bread." ". $i; ?></a>
</div>
<?php if ($i < $count - 1) { ?>
<div class="divider1"></div>
<?php
}
$i++;
}
?>
</div>
<?php } ?>
EDIT: Right link means if you have url like www.homepage.com/mens_where/mens_jackets/Jacket123
Output should be something like that if i don't consider echo-ing classes in upper code
<a href="www.homepage.com">home</a>
<a href="www.homepage.com/mens_wear">Mens Wear</a>
<a href="www.homepage.com/mens_wear/mens_jackets">Mens jackets</a>
<a href="www.homepage.com/mens_wear/mens_jackets/Jacket123">Jacket123</a>
This is my final solution!
<?php if (current_url() !== base_url() && current_url() !== base_url() . "home") { ?>
<div class="breadcrumbs">
<?php
$segments = $this->uri->segment_array();
$last_segment = '';?>
<a href="<?php echo base_url(); ?>"><div class="home">Home</div></a>
<div class="divider1"></div>
<?php
foreach ($segments as $segment) {
$last_segment .= '/' . $segment;
?>
<div class="level1" style="margin-left: -6px ;">
<?php
echo '<a href="'.base_url() . substr($last_segment,1) . '">' . ucfirst(str_replace('-', ' ', str_replace('_', ' ', $segment))) . '</a>';
?>
</div>
<div class="divider1"></div>
<?php
}
?>
</div>
<?php } ?><br>
If you are using codeigniter, try something like this:
<div class="breadcrumb">
<?php
$segments = $this->uri->segment_array();
$last_segment = '';
foreach ($segments as $segment) {
$last_segment .= '/' . $segment;
echo '<a href="www.homepage.com' . $last_segment . '">' . ucfirst(str_replace(array('-', '_'), '', $segment)) . '</a>';
}
?>
</div>
And create the dividers with CSS. That way you don't have to do some tricky checks in the PHP code:
.breadcrumb > a + a:before {
color: #CCC;
content: "/ ";
padding: 0 5px;
}