想为博客增加一个面包屑导航,加完之后发现自己的目录也不深,就一级目录,似乎没有太大的必要,折腾了半天,怎么样改过去的还得怎么样改回来,记录一下代码,以备不时之需,首先将以下代码添加至wordpress的“functions.php”文件中:
function get_breadcrumbs()
{
global $wp_query;
if ( !is_home() ){
// Start the UL
echo '<ul>';
// Add the Home link
echo '<li><a href="'. get_settings('home') .'">'. 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="'. 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”文件的某处,添加如下代码:
<?php
if (function_exists('get_breadcrumbs')){
get_breadcrumbs();
}
?>