23

このスクリプトは、私を含むこのあたりの初心者にとって非常に興味深いものだと思います:)

私が作成したいのは、任意のファイルで使用できる小さなコードであり、次のようなブレッドクラムを生成します。

ファイルの名前が「website.com/templates/index.php」の場合、ブレッドクラムには次のように表示されます。

Website.com > Templates

 ^^リンク^^プレーンテキスト

ファイルの名前が「website.com/templates/template_some_name.php」の場合、ブレッドクラムには次のように表示されます。

Website.com > Templates > Template Some Name

 ^^リンク^^リンク^^プレーンテキスト

4

11 に答える 11

50

これは単純なブレッドクラムにはやり過ぎかもしれませんが、一見の価値があります。私が最初に始めたとき、私はずっと前にこの問題を抱えていたのを覚えています、しかし私はそれを本当に解決したことはありませんでした。つまり、私が今これを書くことに決めたまでです。:)

インラインでできる限り文書化しました。下部には、考えられる3つのユースケースがあります。楽しみ!(ご不明な点がございましたら、お気軽にお問い合わせください)

<?php

// This function will take $_SERVER['REQUEST_URI'] and build a breadcrumb based on the user's current path
function breadcrumbs($separator = ' &raquo; ', $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>
于 2010-04-07T17:42:58.323 に答える
31

うーん、あなたが与えた例から、それは「$ _ SERVER ['REQUEST_URI']」のように見え、explode ()関数があなたを助けることができます。explodeを使用して、ドメイン名に続くURLを配列に分割し、スラッシュごとに区切ることができます。

非常に基本的な例として、次のようなものを実装できます。

$crumbs = explode("/",$_SERVER["REQUEST_URI"]);
foreach($crumbs as $crumb){
    echo ucfirst(str_replace(array(".php","_"),array(""," "),$crumb) . ' ');
}
于 2010-04-07T16:39:14.373 に答える
8

また、RDFaを使用して小さなスクリプトを作成しました(microdataまたは他の形式も使用できます)googleでチェックしてください このスクリプトは、サイトの構造も念頭に置いています。

function breadcrumbs($text = 'You are here: ', $sep = ' &raquo; ', $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;}
于 2012-07-28T20:47:22.790 に答える
4

Dominic Barnesのコードから始め、cWoDeRからのフィードバックを取り入れましたが、サブディレクトリを使用した場合でも、第3レベルのブレッドクラムで問題が発生しました。だから私はそれを書き直して、以下のコードを含めました。

ルートレベルのページに従属する(リンクされる)ページが次のように設定されるように、Webサイトの構造を設定していることに注意してください。

  • ルートレベルのフォルダーとして、ファイルとまったく同じ名前(大文字と小文字を除く)からサフィックスを除いたフォルダーを作成します

  • すべての従属ファイル/ページをこのフォルダーに配置します

(たとえば、Customers.phpのsobordinateページが必要な場合:

  • Customers.phpと同じレベルにCustomersというフォルダを作成します

  • 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 = ""を設定します(末尾の "/"はそのままにしないでください)。Webサイトのサブディレクトリを使用する場合(つまり、/ 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 = ' &raquo; ' , $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>
?>
于 2013-03-07T01:16:11.027 に答える
4

を使用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>';
}

(擬似コード)

于 2010-04-07T16:51:27.643 に答える
2

ちょっと支配的なあなたの答えは良かったですが、http://localhost/project/index.phpのようなサイトがある場合、それは$ 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));
于 2011-02-04T10:17:03.813 に答える
2

これは、非常にシンプルで動的なブレッドクラムです(必要に応じて微調整します)。

    <?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>&nbsp;</span></a></li>';
    }
}
echo '</ol>';
?>
于 2014-01-29T04:53:12.643 に答える
1

explode()関数を使用するより良いものは次のとおりです...

ハイパーリンクのURL変数を置き換えることを忘れないでください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 .= '/';
         }
     }
?>
于 2015-02-20T13:10:27.823 に答える
1

これが懐疑的な答えに基づく私の解決策です。ラテン文字に問題があるため、URLではなくWordPress DBからページタイトルを取得します(スラッグにはラテン文字がありません)。「ホーム」アイテムを表示するかどうかを選択することもできます。

/**
 * 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>
于 2019-12-06T13:09:57.510 に答える
0

これは私が自分のサイトで個人的に使用しているコードです。箱の外で動作します。

<?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のパディングとマージンを自由に試してみてください。

于 2018-11-17T21:46:05.883 に答える
0
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 ? '&raquo;' :'');

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

endforeach;

return $links; 

}

于 2020-05-27T00:11:07.750 に答える