麪包屑導航 (Breadcrumbs) 是網頁導航設計中一個標準設計模式,在網站瀏覽中非常有用。
在 WordPress 主題開發過程中,在文章頁面或者獨立頁面經常需要添加麪包屑導航來優化網站得 SEO,眾多 SEOer 一致認為,給網站添加麪包屑導航有利於提高訪客體驗和搜索引擎優化,所以大多數網站都設計了麪包屑導航。
先看看顯示效果:
![]()
WordPress 麪包屑導航製作方法如下:
1 、在你當前主題的 functions.php 文件添加如下代碼:
function get_breadcrumbs()
{
global $wp_query;
if ( !is_home() ){
// Start the UL
echo '<ul >';
// Add the Home link
echo '<li><a href="'.%20get_settings('home')%20.'">'. get_bloginfo('name') .'</a></li>';
if ( is_category() )
{
$catTitle = single_cat_title( "", false );
$cat = get_cat_ID( $catTitle );
echo "<li> » ". get_category_parents( $cat, TRUE, " » " ) ."</li>";
}
elseif ( is_archive() && !is_category() )
{
echo "<li> » Archives</li>";
}
elseif ( is_search() ) {
echo "<li> » Search Results</li>";
}
elseif ( is_404() )
{
echo "<li> » 404 Not Found</li>";
}
elseif ( is_single() )
{
$category = get_the_category();
$category_id = get_cat_ID( $category[0]->cat_name );
echo '<li> » '. get_category_parents( $category_id, TRUE, " » " );
echo the_title('','', FALSE) ."</li>";
}
elseif ( is_page() )
{
$post = $wp_query->get_queried_object();
if ( $post->post_parent == 0 ){
echo "<li> » ".the_title('','', FALSE)."</li>";
} else {
$title = the_title('','', FALSE);
$ancestors = array_reverse( get_post_ancestors( $post->ID ) );
array_push($ancestors, $post->ID);
foreach ( $ancestors as $ancestor ){
if( $ancestor != end($ancestors) ){
echo '<li> » <a href="'.%20get_permalink($ancestor)%20.'">'. strip_tags( apply_filters( 'single_post_title', get_the_title( $ancestor ) ) ) .'</a></li>';
} else {
echo '<li> » '. strip_tags( apply_filters( 'single_post_title', get_the_title( $ancestor ) ) ) .'</li>';
}
}
}
}
// End the UL
echo "</ul>";
}
}
2 、在需要使用到的麪包屑導航頁面位置添加以下調用代碼:
<?php
if (function_exists('get_breadcrumbs')){
get_breadcrumbs();
}
?>
3. 在主題的 css 樣式文件中添加以下樣式代碼:
ul.breadcrumbs {
list-style: none;
padding: 0;
margin: 0;
font-size:12px;
}
ul.breadcrumbs li {
float: left;
margin: 0 5px 0 0;
padding: 0;
}