默認的WordPress程序是沒有面包屑導航功能的,我們需要通過第三方插件或者修改代碼來實現。因為有了這個功能,能夠有利于用戶體驗,也有利于網站的流量轉化。面包屑導航的作用是告訴訪問者他們目前在網站中的位置以及如何返回。給網站添加面包屑導航有利于提高訪客體驗和搜索引擎優化,所以大多數網站都設計了面包屑導航。下面就來介紹一個用添加代碼來實現面包屑導航功能的方法:
在你的wordpress博客當前所使用主題的functions.php文件(沒有就創建一個)中添加以下代碼:
//面包屑導航
function get_breadcrumbs()
{
global $wp_query;
if ( !is_home() ){
// Start the UL
echo '<ul>';
// Add the Home link
echo '<a href="'. get_settings('home') .'">'. 首頁 .'</a>';
if ( is_category() )
{
$catTitle = single_cat_title( "", false );
$cat = get_cat_ID( $catTitle );
echo " » ". get_category_parents( $cat, TRUE, " » " ) ;
}
elseif ( is_archive() && !is_category() )
{
echo "» Archives";
}
elseif ( is_search() ) {
echo "» Search Results";
}
elseif ( is_404() )
{
echo "» 404 Not Found";
}
elseif ( is_single() )
{
$category = get_the_category();
$category_id = get_cat_ID( $category[0]->cat_name );
echo '» '. get_category_parents( $category_id, TRUE, " » " );
echo the_title('','', FALSE);
}
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="'. get_permalink($ancestor) .'">'. 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>";
}
}
然后在你需要顯示面包屑導航的位置添加以下調用代碼(我是添加在header.php最下面的):
<div class="breadcrumbs">
<?php if (function_exists('get_breadcrumbs')){get_breadcrumbs();} ?>
</div>
在主題的css樣式文件中(style.css)添加以下樣式代碼(可以修改為你自己喜歡的樣式):
/* 面包屑導航 */
.breadcrumbs {
list-style: none;
font-size:14px;
padding: 0px 15px 0px 15px;
margin: 0px 5px 0px 5px;
background:#fafafa;
border:1px solid #dedede;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
border-radius: 6px;
}