简单的动态面包屑

发布于 2024-08-28 12:32:38 字数 686 浏览 11 评论 0原文

我认为这个脚本对这里的任何菜鸟都很感兴趣:)包括我:)

我想要创建的是一些可以在任何文件中使用的小代码,并将生成如下所示的面包屑:

如果该文件名为“< em>website.com/templates/index.php”面包屑应显示:

Website.com > Templates

^^ 链接            ;       ^^纯文本

如果文件名为“website.com/templates/template_some_name.php”,面包屑应显示:

Website.com > Templates > Template Some Name

 ^ ^ 链接            ^^链接    &n公共服务提供商;          ^^纯文本

I think this script is of big interest to any noob around here :) including me :)

What I want to create is a little code that I can use in any file and will generate a breadcrumb like this:

If the file is called "website.com/templates/index.php" the breadcrumb should show:

Website.com > Templates

 ^^ link                    ^^plain text

If the file is called "website.com/templates/template_some_name.php" the breadcrumb should show:

Website.com > Templates > Template Some Name

 ^^ link                   ^^link                ^^plain text

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

如日中天 2024-09-04 12:32:38

对于简单的面包屑来说,这可能有点过分了,但值得一试。我记得很久以前刚开始的​​时候就遇到过这个问题,但一直没有真正解决。也就是说,直到我决定现在写下这篇文章。 :)

我已经尽可能内联地记录了,底部是 3 个可能的用例。享受! (如有任何问题,请随时提出)

<?php

// This function will take $_SERVER['REQUEST_URI'] and build a breadcrumb based on the user's current path
function breadcrumbs($separator = ' » ', $home = 'Home') {
    // This gets the REQUEST_URI (/path/to/file.php), splits the string (using '/') into an array, and then filters out any empty values
    $path = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));

    // This will build our "base URL" ... Also accounts for HTTPS :)
    $base = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';

    // Initialize a temporary array with our breadcrumbs. (starting with our home page, which I'm assuming will be the base URL)
    $breadcrumbs = Array("<a href=\"$base\">$home</a>");

    // Find out the index for the last value in our path array
    $last = end(array_keys($path));

    // Build the rest of the breadcrumbs
    foreach ($path AS $x => $crumb) {
        // Our "title" is the text that will be displayed (strip out .php and turn '_' into a space)
        $title = ucwords(str_replace(Array('.php', '_'), Array('', ' '), $crumb));

        // If we are not on the last index, then display an <a> tag
        if ($x != $last)
            $breadcrumbs[] = "<a href=\"$base$crumb\">$title</a>";
        // Otherwise, just display the title (minus)
        else
            $breadcrumbs[] = $title;
    }

    // Build our temporary array (pieces of bread) into one big string :)
    return implode($separator, $breadcrumbs);
}

?>

<p><?= breadcrumbs() ?></p>
<p><?= breadcrumbs(' > ') ?></p>
<p><?= breadcrumbs(' ^^ ', 'Index') ?></p>

This may be overkill for a simple breadcrumb, but it's worth a shot. I remember having this issue a long time ago when I first started, but I never really solved it. That is, until I just decided to write this up now. :)

I have documented as best I can inline, at the bottom are 3 possible use cases. Enjoy! (feel free to ask any questions you may have)

<?php

// This function will take $_SERVER['REQUEST_URI'] and build a breadcrumb based on the user's current path
function breadcrumbs($separator = ' » ', $home = 'Home') {
    // This gets the REQUEST_URI (/path/to/file.php), splits the string (using '/') into an array, and then filters out any empty values
    $path = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));

    // This will build our "base URL" ... Also accounts for HTTPS :)
    $base = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';

    // Initialize a temporary array with our breadcrumbs. (starting with our home page, which I'm assuming will be the base URL)
    $breadcrumbs = Array("<a href=\"$base\">$home</a>");

    // Find out the index for the last value in our path array
    $last = end(array_keys($path));

    // Build the rest of the breadcrumbs
    foreach ($path AS $x => $crumb) {
        // Our "title" is the text that will be displayed (strip out .php and turn '_' into a space)
        $title = ucwords(str_replace(Array('.php', '_'), Array('', ' '), $crumb));

        // If we are not on the last index, then display an <a> tag
        if ($x != $last)
            $breadcrumbs[] = "<a href=\"$base$crumb\">$title</a>";
        // Otherwise, just display the title (minus)
        else
            $breadcrumbs[] = $title;
    }

    // Build our temporary array (pieces of bread) into one big string :)
    return implode($separator, $breadcrumbs);
}

?>

<p><?= breadcrumbs() ?></p>
<p><?= breadcrumbs(' > ') ?></p>
<p><?= breadcrumbs(' ^^ ', 'Index') ?></p>
篱下浅笙歌 2024-09-04 12:32:38

嗯,从您给出的示例来看,它看起来像“$_SERVER['REQUEST_URI']”和 explode() 函数可以帮助你。您可以使用explode 将域名后面的URL 分解为一个数组,并在每个正斜杠处将其分隔开。

作为一个非常基本的例子,可以实现这样的事情:

$crumbs = explode("/",$_SERVER["REQUEST_URI"]);
foreach($crumbs as $crumb){
    echo ucfirst(str_replace(array(".php","_"),array(""," "),$crumb) . ' ');
}

Hmm, from the examples you gave it seems like "$_SERVER['REQUEST_URI']" and the explode() function could help you. You could use explode to break up the URL following the domain name into an array, separating it at each forward-slash.

As a very basic example, something like this could be implemented:

$crumbs = explode("/",$_SERVER["REQUEST_URI"]);
foreach($crumbs as $crumb){
    echo ucfirst(str_replace(array(".php","_"),array(""," "),$crumb) . ' ');
}
很酷又爱笑 2024-09-04 12:32:38

还使用 RDFa 制作了一个小脚本(您也可以使用微数据或其他格式)在 google 上查看
该脚本还会记住您的站点结构。

function breadcrumbs($text = 'You are here: ', $sep = ' » ', $home = 'Home') {
//Use RDFa breadcrumb, can also be used for microformats etc.
$bc     =   '<div xmlns:v="http://rdf.data-vocabulary.org/#" id="crums">'.$text;
//Get the website:
$site   =   'http://'.$_SERVER['HTTP_HOST'];
//Get all vars en skip the empty ones
$crumbs =   array_filter( explode("/",$_SERVER["REQUEST_URI"]) );
//Create the home breadcrumb
$bc    .=   '<span typeof="v:Breadcrumb"><a href="'.$site.'" rel="v:url" property="v:title">'.$home.'</a>'.$sep.'</span>'; 
//Count all not empty breadcrumbs
$nm     =   count($crumbs);
$i      =   1;
//Loop the crumbs
foreach($crumbs as $crumb){
    //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;
    //Make the next crumb
    $bc     .=  '<span typeof="v:Breadcrumb"><a href="'.$site.'" rel="v:url" property="v:title">'.$link.'</a>'.$sep.'</span>';
    $i++;
}
$bc .=  '</div>';
//Return the result
return $bc;}

Also made a little script using RDFa (you can also use microdata or other formats) Check it out on google
This script also keeps in mind your site structure.

function breadcrumbs($text = 'You are here: ', $sep = ' » ', $home = 'Home') {
//Use RDFa breadcrumb, can also be used for microformats etc.
$bc     =   '<div xmlns:v="http://rdf.data-vocabulary.org/#" id="crums">'.$text;
//Get the website:
$site   =   'http://'.$_SERVER['HTTP_HOST'];
//Get all vars en skip the empty ones
$crumbs =   array_filter( explode("/",$_SERVER["REQUEST_URI"]) );
//Create the home breadcrumb
$bc    .=   '<span typeof="v:Breadcrumb"><a href="'.$site.'" rel="v:url" property="v:title">'.$home.'</a>'.$sep.'</span>'; 
//Count all not empty breadcrumbs
$nm     =   count($crumbs);
$i      =   1;
//Loop the crumbs
foreach($crumbs as $crumb){
    //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;
    //Make the next crumb
    $bc     .=  '<span typeof="v:Breadcrumb"><a href="'.$site.'" rel="v:url" property="v:title">'.$link.'</a>'.$sep.'</span>';
    $i++;
}
$bc .=  '</div>';
//Return the result
return $bc;}
坐在坟头思考人生 2024-09-04 12:32:38

使用 parse_url 然后循环输出结果:(

$urlinfo = parse_url($the_url);
echo makelink($urlinfo['hostname']);
foreach($breadcrumb in $urlinfo['path']) {
  echo makelink($breadcrumb);
}

function makelink($str) {
  return '<a href="'.urlencode($str).'" title="'.htmlspecialchars($str).'">'.htmlspecialchars($str).'</a>';
}

伪代码)

use parse_url and then output the result in a loop:

$urlinfo = parse_url($the_url);
echo makelink($urlinfo['hostname']);
foreach($breadcrumb in $urlinfo['path']) {
  echo makelink($breadcrumb);
}

function makelink($str) {
  return '<a href="'.urlencode($str).'" title="'.htmlspecialchars($str).'">'.htmlspecialchars($str).'</a>';
}

(pseudocode)

只是一片海 2024-09-04 12:32:38

我从 Dominic Barnes 的代码开始,结合了 cWoDeR 的反馈,当我使用子目录时,我在第三层的面包屑中仍然遇到问题。所以我重写了它并包含了下面的代码。

请注意,我已经设置了我的网站结构,以便从属于(链接自)根级别页面的页面设置如下:

  • 创建一个与文件名称完全相同的文件夹(包括大小写) ),减去后缀,作为根级别的文件夹

  • 放置所有下级文件夹文件/页面放入此文件夹

(例如,如果需要 Customers.php 的附属页面:

  • 创建一个名为 Customers 的文件夹,与 Customers.php 处于同一级别

  • 将一个 index.php 文件添加到 Customers 文件夹中,该文件重定向到该文件夹​​的调用页面(请参阅下面的代码)

此结构适用于多层子文件夹。

只需确保遵循上述文件结构,并插入一个包含每个子文件夹中显示的代码的 index.php 文件。

每个子文件夹中的index.php页面中的代码如下所示:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Redirected</title>
</head>
<body>
<?php 
$root_dir = "web_root/" ;
$last_dir=array_slice(array_filter(explode('/',$_SERVER['PHP_SELF'])),-2,1,false) ;
$path_to_redirect = "/".$root_dir.$last_dir[0].".php" ; 
header('Location: '.$path_to_redirect) ; 
?>
</body>
</html>

如果您使用服务器的根目录作为您的Web根(即/var/www/html),则设置$root_dir =“”:(不要留下尾随“/“ 在)。如果您的网站使用子目录(即 /var/www/html/web_root,则设置 $root_dir = "web_root/"; (将 web_root 替换为您的 Web 目录的实际名称)(确保包含尾随 /)

无论如何,这是我的(衍生)代码:

<?php

// Big Thank You to the folks on StackOverflow
// See http://stackoverflow.com/questions/2594211/php-simple-dynamic-breadcrumb
// Edited to enable using subdirectories to /var/www/html as root
// eg, using /var/www/html/<this folder> as the root directory for this web site
// To enable this, enter the name of the subdirectory being used as web root
// in the $directory2 variable below
// Make sure to include the trailing "/" at the end of the directory name
// eg use      $directory2="this_folder/" ;
// do NOT use  $directory2="this_folder" ;
// If you actually ARE using /var/www/html as the root directory,
// just set $directory2 = "" (blank)
// with NO trailing "/"

// This function will take $_SERVER['REQUEST_URI'] and build a breadcrumb based on the user's current path
function breadcrumbs($separator = ' » ' , $home = 'Home') 
{

    // This sets the subdirectory as web_root (If you want to use a subdirectory)
    // If you do not use a web_root subdirectory, set $directory2=""; (NO trailing /)
    $directory2 = "web_root/" ;

    // This gets the REQUEST_URI (/path/to/file.php), splits the string (using '/') into an array, and then filters out any empty values
    $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ;
    $path_array = array_filter(explode('/',$path)) ;

    // This line of code accommodates using a subfolder (/var/www/html/<this folder>) as root
    // This removes the first item in the array path so it doesn't repeat
    if ($directory2 != "")
    {
    array_shift($path_array) ;
    }

    // This will build our "base URL" ... Also accounts for HTTPS :)
    $base = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/'. $directory2 ;

    // Initialize a temporary array with our breadcrumbs. (starting with our home page, which I'm assuming will be the base URL)
    $breadcrumbs = Array("<a href=\"$base\">$home</a>") ;

    // Get the index for the last value in our path array
    $last = end($path_array) ;

    // Initialize the counter
    $crumb_counter = 2 ;

    // Build the rest of the breadcrumbs
    foreach ($path_array as $crumb) 
    {
        // Our "title" is the text that will be displayed representing the filename without the .suffix
        // If there is no "." in the crumb, it is a directory
        if (strpos($crumb,".") == false)
        {
            $title = $crumb ;
        }
        else
        {
            $title = substr($crumb,0,strpos($crumb,".")) ;
        }

        // If we are not on the last index, then create a hyperlink
        if ($crumb != $last)
        {
            $calling_page_array = array_slice(array_values(array_filter(explode('/',$path))),0,$crumb_counter,false) ;
            $calling_page_path = "/".implode('/',$calling_page_array).".php" ;
            $breadcrumbs[] = "<a href=".$calling_page_path.">".$title."</a>" ;
        }

        // Otherwise, just display the title
        else
        {
            $breadcrumbs[] = $title ;
        }

        $crumb_counter = $crumb_counter + 1 ;

    }
    // Build our temporary array (pieces of bread) into one big string :)
    return implode($separator, $breadcrumbs) ;
}

// <p><?= breadcrumbs() ? ></p>
// <p><?= breadcrumbs(' > ') ? ></p>
// <p><?= breadcrumbs(' ^^ ', 'Index') ? ></p>
?>

I started with the code from Dominic Barnes, incorporated the feedback from cWoDeR and I still had problems with the breadcrumbs at the third level when I used a sub-directory. So I rewrote it and have included the code below.

Note that I have set up my web site structure such that pages to be subordinate to (linked from) a page at the root level are set up as follows:

  • Create a folder with the EXACT same name as the file (including capitalization), minus the suffix, as a folder at the root level

  • place all subordinate files/pages into this folder

(eg, if want sobordinate pages for Customers.php:

  • create a folder called Customers at the same level as Customers.php

  • add an index.php file into the Customers folder which redirects to the calling page for the folder (see below for code)

This structure will work for multiple levels of subfolders.

Just make sure you follow the file structure described above AND insert an index.php file with the code shown in each subfolder.

The code in the index.php page in each subfolder looks like:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Redirected</title>
</head>
<body>
<?php 
$root_dir = "web_root/" ;
$last_dir=array_slice(array_filter(explode('/',$_SERVER['PHP_SELF'])),-2,1,false) ;
$path_to_redirect = "/".$root_dir.$last_dir[0].".php" ; 
header('Location: '.$path_to_redirect) ; 
?>
</body>
</html>

If you use the root directory of the server as your web root (ie /var/www/html) then set $root_dir="": (do NOT leave the trailing "/" in). If you use a subdirectory for your web site (ie /var/www/html/web_root then set $root_dir = "web_root/"; (replace web_root with the actual name of your web directory)(make sure to include the trailing /)

at any rate, here is my (derivative) code:

<?php

// Big Thank You to the folks on StackOverflow
// See http://stackoverflow.com/questions/2594211/php-simple-dynamic-breadcrumb
// Edited to enable using subdirectories to /var/www/html as root
// eg, using /var/www/html/<this folder> as the root directory for this web site
// To enable this, enter the name of the subdirectory being used as web root
// in the $directory2 variable below
// Make sure to include the trailing "/" at the end of the directory name
// eg use      $directory2="this_folder/" ;
// do NOT use  $directory2="this_folder" ;
// If you actually ARE using /var/www/html as the root directory,
// just set $directory2 = "" (blank)
// with NO trailing "/"

// This function will take $_SERVER['REQUEST_URI'] and build a breadcrumb based on the user's current path
function breadcrumbs($separator = ' » ' , $home = 'Home') 
{

    // This sets the subdirectory as web_root (If you want to use a subdirectory)
    // If you do not use a web_root subdirectory, set $directory2=""; (NO trailing /)
    $directory2 = "web_root/" ;

    // This gets the REQUEST_URI (/path/to/file.php), splits the string (using '/') into an array, and then filters out any empty values
    $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ;
    $path_array = array_filter(explode('/',$path)) ;

    // This line of code accommodates using a subfolder (/var/www/html/<this folder>) as root
    // This removes the first item in the array path so it doesn't repeat
    if ($directory2 != "")
    {
    array_shift($path_array) ;
    }

    // This will build our "base URL" ... Also accounts for HTTPS :)
    $base = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/'. $directory2 ;

    // Initialize a temporary array with our breadcrumbs. (starting with our home page, which I'm assuming will be the base URL)
    $breadcrumbs = Array("<a href=\"$base\">$home</a>") ;

    // Get the index for the last value in our path array
    $last = end($path_array) ;

    // Initialize the counter
    $crumb_counter = 2 ;

    // Build the rest of the breadcrumbs
    foreach ($path_array as $crumb) 
    {
        // Our "title" is the text that will be displayed representing the filename without the .suffix
        // If there is no "." in the crumb, it is a directory
        if (strpos($crumb,".") == false)
        {
            $title = $crumb ;
        }
        else
        {
            $title = substr($crumb,0,strpos($crumb,".")) ;
        }

        // If we are not on the last index, then create a hyperlink
        if ($crumb != $last)
        {
            $calling_page_array = array_slice(array_values(array_filter(explode('/',$path))),0,$crumb_counter,false) ;
            $calling_page_path = "/".implode('/',$calling_page_array).".php" ;
            $breadcrumbs[] = "<a href=".$calling_page_path.">".$title."</a>" ;
        }

        // Otherwise, just display the title
        else
        {
            $breadcrumbs[] = $title ;
        }

        $crumb_counter = $crumb_counter + 1 ;

    }
    // Build our temporary array (pieces of bread) into one big string :)
    return implode($separator, $breadcrumbs) ;
}

// <p><?= breadcrumbs() ? ></p>
// <p><?= breadcrumbs(' > ') ? ></p>
// <p><?= breadcrumbs(' ^^ ', 'Index') ? ></p>
?>
も让我眼熟你 2024-09-04 12:32:38

嘿多米尼克,你的回答很好,但是如果你有一个像 http://localhost/project/index.php “project”链接会重复,因为它是 $base 的一部分,并且也出现在 $path 数组中。所以我调整并删除了 $path 数组中的第一项。

//Trying to remove the first item in the array path so it doesn't repeat
array_shift($path);

我不知道这是否是最优雅的方式,但它现在对我有用。

我在第 13 行或其他地方添加了该代码之前

// Find out the index for the last value in our path array
$last = end(array_keys($path));

hey dominic your answer was nice but if your have a site like http://localhost/project/index.php the 'project' link gets repeated since it's part of $base and also appears in the $path array. So I tweaked and removed the first item in the $path array.

//Trying to remove the first item in the array path so it doesn't repeat
array_shift($path);

I dont know if that is the most elegant way, but it now works for me.

I add that code before this one on line 13 or something

// Find out the index for the last value in our path array
$last = end(array_keys($path));
花心好男孩 2024-09-04 12:32:38

这是一个很棒的简单动态面包屑(根据需要进行调整):

    <?php 
    $docroot = "/zen/index5.php";
    $path =($_SERVER['REQUEST_URI']);
    $names = explode("/", $path); 
    $trimnames = array_slice($names, 1, -1);
    $length = count($trimnames)-1;
    $fixme = array(".php","-","myname");
    $fixes = array(""," ","My<strong>Name</strong>");
    echo '<div id="breadwrap"><ol id="breadcrumb">';
    $url = "";
    for ($i = 0; $i <= $length;$i++){
    $url .= $trimnames[$i]."/";
        if($i>0 && $i!=$length){
            echo '<li><a href="/'.$url.'">'.ucfirst(str_replace($fixme,$fixes,$trimnames[$i]) . ' ').'</a></li>';
    }
    elseif ($i == $length){
        echo '<li class="current">'.ucfirst(str_replace($fixme,$fixes,$trimnames[$i]) . ' ').'</li>';       
    }
    else{
        echo $trimnames[$i]='<li><a href='.$docroot.' id="bread-home"><span> </span></a></li>';
    }
}
echo '</ol>';
?>

Here is a great simple dynamic breadcrumb (tweak as needed):

    <?php 
    $docroot = "/zen/index5.php";
    $path =($_SERVER['REQUEST_URI']);
    $names = explode("/", $path); 
    $trimnames = array_slice($names, 1, -1);
    $length = count($trimnames)-1;
    $fixme = array(".php","-","myname");
    $fixes = array(""," ","My<strong>Name</strong>");
    echo '<div id="breadwrap"><ol id="breadcrumb">';
    $url = "";
    for ($i = 0; $i <= $length;$i++){
    $url .= $trimnames[$i]."/";
        if($i>0 && $i!=$length){
            echo '<li><a href="/'.$url.'">'.ucfirst(str_replace($fixme,$fixes,$trimnames[$i]) . ' ').'</a></li>';
    }
    elseif ($i == $length){
        echo '<li class="current">'.ucfirst(str_replace($fixme,$fixes,$trimnames[$i]) . ' ').'</li>';       
    }
    else{
        echo $trimnames[$i]='<li><a href='.$docroot.' id="bread-home"><span> </span></a></li>';
    }
}
echo '</ol>';
?>
奢欲 2024-09-04 12:32:38

使用 explode() 函数的更好方法如下...

不要忘记替换超链接 href 中的 URL 变量。

<?php 
    if($url != ''){
        $b = '';
        $links = explode('/',rtrim($url,'/'));
        foreach($links as $l){
            $b .= $l;
            if($url == $b){
                echo $l;
            }else{
                echo "<a href='URL?url=".$b."'>".$l."/</a>";
            }
            $b .= '/';
         }
     }
?>

A better one using explode() function is as follows...

Don't forget to replace your URL variable in the hyperlink href.

<?php 
    if($url != ''){
        $b = '';
        $links = explode('/',rtrim($url,'/'));
        foreach($links as $l){
            $b .= $l;
            if($url == $b){
                echo $l;
            }else{
                echo "<a href='URL?url=".$b."'>".$l."/</a>";
            }
            $b .= '/';
         }
     }
?>
阳光下慵懒的猫 2024-09-04 12:32:38

这是我基于怀疑论答案的解决方案。它从 WordPress DB 获取页面标题,而不是从 URL 获取,因为存在拉丁字符问题(slug 没有拉丁字符)。您还可以选择是否显示“主页”项目。

/**
 * Show Breadcrumbs
 * 
 * @param string|bool $home
 * @param string $class
 * @return string
 * 
 * Using: echo breadcrumbs();
 */
function breadcrumbs($home = 'Home', $class = 'items') {
    $breadcrumb  = '<ul class="'. $class .'">';
    $breadcrumbs = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));

    if ($home) {
        $breadcrumb .= '<li><a href="' . get_site_url() . '">' . $home . '</a></li>';
    }

    $path = '';
    foreach ($breadcrumbs as $crumb) {
        $path .=  $crumb . '/';
        $page = get_page_by_path($path);

        if ($home && ($page->ID == get_option('page_on_front'))) {
            continue;
        }

        $breadcrumb .= '<li><a href="'. get_permalink($page) .'">' . $page->post_title . '</a></li>';
    }

    $breadcrumb .= '</ul>';
    return $breadcrumb;
}

使用:

<div class="breadcrumb">
    <div class="container">
        <h3 class="breadcrumb__title">Jazda na maxa!</h3>
        <?php echo breadcrumbs('Start', 'breadcrumb__items'); ?>
    </div>
</div>

Here is my solution based on Skeptic answer. It gets page title from WordPress DB, not from URL because there is a problem with latin characters (slug doesn't has a latin characters). You can also choose to display "home" item or not.

/**
 * Show Breadcrumbs
 * 
 * @param string|bool $home
 * @param string $class
 * @return string
 * 
 * Using: echo breadcrumbs();
 */
function breadcrumbs($home = 'Home', $class = 'items') {
    $breadcrumb  = '<ul class="'. $class .'">';
    $breadcrumbs = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));

    if ($home) {
        $breadcrumb .= '<li><a href="' . get_site_url() . '">' . $home . '</a></li>';
    }

    $path = '';
    foreach ($breadcrumbs as $crumb) {
        $path .=  $crumb . '/';
        $page = get_page_by_path($path);

        if ($home && ($page->ID == get_option('page_on_front'))) {
            continue;
        }

        $breadcrumb .= '<li><a href="'. get_permalink($page) .'">' . $page->post_title . '</a></li>';
    }

    $breadcrumb .= '</ul>';
    return $breadcrumb;
}

Using:

<div class="breadcrumb">
    <div class="container">
        <h3 class="breadcrumb__title">Jazda na maxa!</h3>
        <?php echo breadcrumbs('Start', 'breadcrumb__items'); ?>
    </div>
</div>
女皇必胜 2024-09-04 12:32:38

这是我个人在我的网站中使用的代码。在盒子之外工作。

<?php
function breadcrumbs($home = 'Home') {
  global $page_title; //global varable that takes it's value from the page that breadcrubs will appear on. Can be deleted if you wish, but if you delete it, delete also the title tage inside the <li> tag inside the foreach loop.
    $breadcrumb  = '<div class="breadcrumb-container"><div class="container"><ol class="breadcrumb">';
    $root_domain = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'].'/';
    $breadcrumbs = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
    $breadcrumb .= '<li><i class="fa fa-home"></i><a href="' . $root_domain . '" title="Home Page"><span>' . $home . '</span></a></li>';
    foreach ($breadcrumbs as $crumb) {
        $link = ucwords(str_replace(array(".php","-","_"), array(""," "," "), $crumb));
        $root_domain .=  $crumb . '/';
        $breadcrumb .= '<li><a href="'. $root_domain .'" title="'.$page_title.'"><span>' . $link . '</span></a></li>';
    }
    $breadcrumb .= '</ol>';
    $breadcrumb .= '</div>';
    $breadcrumb .= '</div>';
    return $breadcrumb;
}
echo breadcrumbs();
?>

CSS:

.breadcrumb-container {
    width: 100%;
    background-color: #f8f8f8;
    border-bottom-color: 1px solid #f4f4f4;
    list-style: none;
    margin-top: 72px;
    min-height: 25px;
    box-shadow: 0 3px 0 rgba(60, 57, 57, .2)
}

.breadcrumb-container li {
    display: inline
}
.breadcrumb {
    font-size: 12px;
    padding-top: 3px
}
.breadcrumb>li:last-child:after {
    content: none
}

.breadcrumb>li:last-child {
    font-weight: 700;
    font-style: italic
}
.breadcrumb>li>i {
    margin-right: 3px
}

.breadcrumb>li:after {
    font-family: FontAwesome;
    content: "\f101";
    font-size: 11px;
    margin-left: 3px;
    margin-right: 3px
}
.breadcrumb>li+li:before {
    font-size: 11px;
    padding-left: 3px
}

随意调整 CSS 内边距和边距,直到适合您自己的网站为止。

This is the code that i personally use in my sites. Works outside of the box.

<?php
function breadcrumbs($home = 'Home') {
  global $page_title; //global varable that takes it's value from the page that breadcrubs will appear on. Can be deleted if you wish, but if you delete it, delete also the title tage inside the <li> tag inside the foreach loop.
    $breadcrumb  = '<div class="breadcrumb-container"><div class="container"><ol class="breadcrumb">';
    $root_domain = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'].'/';
    $breadcrumbs = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
    $breadcrumb .= '<li><i class="fa fa-home"></i><a href="' . $root_domain . '" title="Home Page"><span>' . $home . '</span></a></li>';
    foreach ($breadcrumbs as $crumb) {
        $link = ucwords(str_replace(array(".php","-","_"), array(""," "," "), $crumb));
        $root_domain .=  $crumb . '/';
        $breadcrumb .= '<li><a href="'. $root_domain .'" title="'.$page_title.'"><span>' . $link . '</span></a></li>';
    }
    $breadcrumb .= '</ol>';
    $breadcrumb .= '</div>';
    $breadcrumb .= '</div>';
    return $breadcrumb;
}
echo breadcrumbs();
?>

The css:

.breadcrumb-container {
    width: 100%;
    background-color: #f8f8f8;
    border-bottom-color: 1px solid #f4f4f4;
    list-style: none;
    margin-top: 72px;
    min-height: 25px;
    box-shadow: 0 3px 0 rgba(60, 57, 57, .2)
}

.breadcrumb-container li {
    display: inline
}
.breadcrumb {
    font-size: 12px;
    padding-top: 3px
}
.breadcrumb>li:last-child:after {
    content: none
}

.breadcrumb>li:last-child {
    font-weight: 700;
    font-style: italic
}
.breadcrumb>li>i {
    margin-right: 3px
}

.breadcrumb>li:after {
    font-family: FontAwesome;
    content: "\f101";
    font-size: 11px;
    margin-left: 3px;
    margin-right: 3px
}
.breadcrumb>li+li:before {
    font-size: 11px;
    padding-left: 3px
}

Feel free to play around with the css padding and margins until you get it right for your own site.

独自←快乐 2024-09-04 12:32:38
function  makeBreadCrumbs($separator = '/'){
        //extract uri path parts into an array
        $breadcrumbs =  array_filter(explode('/',parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));

        //determine the base url or domain 
        $base = (isset($_SERVER['HTTPS'])  ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';

        $last  =  end($breadcrumbs); //obtain the last piece of the path parts
        $crumbs['Home'] = $base; //Our first crumb is the base url 
        $current =  $crumbs['Home']; //set the current breadcrumb to base url

    //create valid urls from the breadcrumbs and store them in an array
    foreach ($breadcrumbs as $key => $piece) {

    //ignore file names and create urls from  directory path
    if( strstr($last,'.php') == false){
        $current   =  $current.$separator.$piece;
        $crumbs[$piece] =$current;

    }else{

        if($piece !== $last){
            $current   =  $current.$separator.$piece;
            $crumbs[$piece] =$current;
        }
    }

    }


    $links = '';
    $count = 0;

//create html tags for displaying the breadcrumbs
foreach ($crumbs as $key => $value) :
    $x = array_filter(explode('/',parse_url($value, PHP_URL_PATH)));
    $last =  end($x);
    //this will add a class to the last link to control its appearance
    $clas = ($count === count($crumbs) -1 ? ' current-crumb' : '' );

    //determine where to print separators 
    $sep = ( $count > -1 && $count < count($crumbs) -1 ? '»' :'');

    $links .= "<a class=\"$clas\" href=\"$value\">$key</a> $sep";
    $count++;

endforeach;

return $links; 

}

function  makeBreadCrumbs($separator = '/'){
        //extract uri path parts into an array
        $breadcrumbs =  array_filter(explode('/',parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));

        //determine the base url or domain 
        $base = (isset($_SERVER['HTTPS'])  ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';

        $last  =  end($breadcrumbs); //obtain the last piece of the path parts
        $crumbs['Home'] = $base; //Our first crumb is the base url 
        $current =  $crumbs['Home']; //set the current breadcrumb to base url

    //create valid urls from the breadcrumbs and store them in an array
    foreach ($breadcrumbs as $key => $piece) {

    //ignore file names and create urls from  directory path
    if( strstr($last,'.php') == false){
        $current   =  $current.$separator.$piece;
        $crumbs[$piece] =$current;

    }else{

        if($piece !== $last){
            $current   =  $current.$separator.$piece;
            $crumbs[$piece] =$current;
        }
    }

    }


    $links = '';
    $count = 0;

//create html tags for displaying the breadcrumbs
foreach ($crumbs as $key => $value) :
    $x = array_filter(explode('/',parse_url($value, PHP_URL_PATH)));
    $last =  end($x);
    //this will add a class to the last link to control its appearance
    $clas = ($count === count($crumbs) -1 ? ' current-crumb' : '' );

    //determine where to print separators 
    $sep = ( $count > -1 && $count < count($crumbs) -1 ? '»' :'');

    $links .= "<a class=\"$clas\" href=\"$value\">$key</a> $sep";
    $count++;

endforeach;

return $links; 

}

如痴如狂 2024-09-04 12:32:38

我还有其他要求,需要一个更灵活的解决方案,即我的网络服务器上“某处”文件夹的面包屑路径,该文件夹不在我网站的文件结构内。因此,我无法在这里使用大多数解决方案。

在我的 Windows 计算机上,路径如下所示:

C:\wamp64\www\VIBE\screening_service\public\患者\病人_00005238\screening 20210608_1827

我希望我的面包屑看起来像这样:

public >患者>病人_00005238>筛查20210608_1827

因此,“public”是开始文件夹(我在代码中将其称为$baseFolder)。

对于拇指的显示文本,我可以获取属于这些文件夹的 URL,但我必须在代码中保留一部分(我将其称为 $baseUrl)。我需要省略的部分:

/VIBE/screening_service/

通过稍后合并 $baseUrl '/VIBE/screening_service/”与“患者/病人_00005238”,您通常可以创建有效的链接。但在我的情况下则不然,因为这些文件夹位于我的网站之外

Web 浏览器会将合并的字符串

'/VIBE/screening_service/ Patients/ Patient_00005238/'

解释为

'< em>http://localhost:8080//VIBE/screening_service/患者/patent_00005238/'。

在我的例子中,我只想要面包屑路径(如“患者/病人_00005238”),我将其添加到面包屑 div 的数据属性中。
我定义了一个 Javascript 单击事件,并将使用数据属性来重建我需要的真实路径。

好吧,这一切导致了这个功能,这可能对某人有用。

像这样调用请

$folder = 'C:\wamp64\www\VIBE\screening_service\public\patients\patient_00005238\screening 20210608_1827';

$baseFolder = 'C:\wamp64\www\VIBE\screening_service\\';
$baseUrl = '/VIBE/screening_service/';

$breadCrumbs = getBreadCrumbs($folder, $baseFolder, $baseUrl, 'crumbs', ' › ', true); 

注意,$baseUrl 映射到 Web 服务器上的 $baseFolder。

function getBreadCrumbs(string $folder, string $baseFolder, string $baseUrl, string $cssClassName = '', string $separator = ' › ', bool $returnLinks = true): string
{
    // Start working with the file system folder structure
    
    // Remove the base folder part we do not want to be part of our crumbs 
    $url = str_replace($baseFolder, '', $folder);
    
    // Replace Windows directroy seperators (backward slashes) with forward slashes
    $url = str_replace('\\', DIRECTORY_SEPERATOR, $url);
    
    // Get the crumbs array from this URL 
    $crumbs = array_filter(explode('/', $url));
    
    // How many crumbs have we?
    $crumbCount = count($crumbs);
    
    // We use the CSS class name for styling our crumbs, if it is not empty 
    $cssClass = empty($cssClassName) ? '' : sprintf(' class="%s"', $cssClassName);
    
    // Start building our crumbs trail (a DIV element and add the (optional CSS class) 
    $trail = sprintf('<div%s>', $cssClass) . PHP_EOL;
    
    // Do we want links? If yes, we have to start them with the $baseUrl
    $crumbUrl = $returnLinks ? rtrim($baseUrl, '/') . '/' : '';    
    
    // Iterate through the crumbs
    foreach($crumbs as $i => $crumb)
    {
        // We create a separator, except for the last crumb
        $sep = $i < $crumbCount-1 ? $separator : '';
        
        // Add the crumb to our crumbs trail
        $crumbUrl .= $crumb . '/';
    
        // Do we want links? If yes, create the link part in our HTML
        $html = $returnLinks ? sprintf('<a href="%s">%s</a>', $crumbUrl, $crumb) : $crumb;
        
        // Wrap our link in a DIV element and add a data attribute with the crumb URL (which can be used in Javascript)   
        $html = sprintf('<div data-crumb="%s">%s</div>', $crumbUrl, $html);
        
        // Add the HTML to our crumbs trail
        $trail .=  $html . $sep . PHP_EOL;       
    }

    // End building our crumbs trail        
    $trail .= '</div>' . PHP_EOL;

    return $trail;
}

I had other requirements and needed a far more flexible solution, a bread crumbs path for a folder 'somewhere' on my web server, which is not within the file structure of my website. Because of this, I can't use most solutions here.

On my Windows machine the path looks like this:

C:\wamp64\www\VIBE\screening_service\public\patients\patient_00005238\screening 20210608_1827

I wanted my breadcrumbs look like this:

public › patients › patient_00005238 › screening 20210608_1827

So, 'public' is the start folder (which I call $baseFolder in my code).

For the displayed text of the thumbs, I can take the URL's which belong to these folders, but I have to leave a part out, (which I will call $baseUrl) in my code. The part I need to leave out:

/VIBE/screening_service/

By later merging $baseUrl '/VIBE/screening_service/' with 'patients/patient_00005238', you can normally create valid links. Not in my case though, because these folders are outside of my website

A web browser will interpret the merged strings

'/VIBE/screening_service/patients/patient_00005238/'

as

'http://localhost:8080//VIBE/screening_service/patients/patient_00005238/'.

In my case I wanted just the crumb path ( like 'patients/patient_00005238' ), which I add to the data attribute of the div of the crumb.
I define a Javascript click event and will use the data attribute to reconstruct the real path I need.

Well all this resulted in this function, which might be useful to somebody.

Call it like this

$folder = 'C:\wamp64\www\VIBE\screening_service\public\patients\patient_00005238\screening 20210608_1827';

$baseFolder = 'C:\wamp64\www\VIBE\screening_service\\';
$baseUrl = '/VIBE/screening_service/';

$breadCrumbs = getBreadCrumbs($folder, $baseFolder, $baseUrl, 'crumbs', ' › ', true); 

Note that $baseUrl maps to $baseFolder on the web server.

function getBreadCrumbs(string $folder, string $baseFolder, string $baseUrl, string $cssClassName = '', string $separator = ' › ', bool $returnLinks = true): string
{
    // Start working with the file system folder structure
    
    // Remove the base folder part we do not want to be part of our crumbs 
    $url = str_replace($baseFolder, '', $folder);
    
    // Replace Windows directroy seperators (backward slashes) with forward slashes
    $url = str_replace('\\', DIRECTORY_SEPERATOR, $url);
    
    // Get the crumbs array from this URL 
    $crumbs = array_filter(explode('/', $url));
    
    // How many crumbs have we?
    $crumbCount = count($crumbs);
    
    // We use the CSS class name for styling our crumbs, if it is not empty 
    $cssClass = empty($cssClassName) ? '' : sprintf(' class="%s"', $cssClassName);
    
    // Start building our crumbs trail (a DIV element and add the (optional CSS class) 
    $trail = sprintf('<div%s>', $cssClass) . PHP_EOL;
    
    // Do we want links? If yes, we have to start them with the $baseUrl
    $crumbUrl = $returnLinks ? rtrim($baseUrl, '/') . '/' : '';    
    
    // Iterate through the crumbs
    foreach($crumbs as $i => $crumb)
    {
        // We create a separator, except for the last crumb
        $sep = $i < $crumbCount-1 ? $separator : '';
        
        // Add the crumb to our crumbs trail
        $crumbUrl .= $crumb . '/';
    
        // Do we want links? If yes, create the link part in our HTML
        $html = $returnLinks ? sprintf('<a href="%s">%s</a>', $crumbUrl, $crumb) : $crumb;
        
        // Wrap our link in a DIV element and add a data attribute with the crumb URL (which can be used in Javascript)   
        $html = sprintf('<div data-crumb="%s">%s</div>', $crumbUrl, $html);
        
        // Add the HTML to our crumbs trail
        $trail .=  $html . $sep . PHP_EOL;       
    }

    // End building our crumbs trail        
    $trail .= '</div>' . PHP_EOL;

    return $trail;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文