Wordpressにパンくずリストを表示
2014/07/04
プラグインを使用するのがてっとりばやいようではあるけど、なるべくプラグインは入れたくないこともあり、functionとして導入した。
下記のコードを functions.php へ挿入、
function the_breadcrumb(){
global $post;
$str ='';
if(!is_home()&&!is_admin()){
$tagAttribute = '';
$str.= '
<div id="bread" class="inner">';
$str.= '<a href="'. home_url() .'/">HOME</a> > ';</div>
if(is_category()) {
//カテゴリーアーカイブ
$cat = get_queried_object();
if($cat -> parent != 0){
$ancestors = array_reverse(get_ancestors( $cat -> cat_ID, 'category' ));
foreach($ancestors as $ancestor){
$str.='<a href="'. get_category_link($ancestor) .'">'. get_cat_name($ancestor) .'</a> > ';
}
}
$str.=''. $cat -> name . '';
} elseif(is_single()){
//ブログ個別記事
$categories = get_the_category($post->ID);
$cat = $categories[0];
if($cat -> parent != 0){
$ancestors = array_reverse(get_ancestors( $cat -> cat_ID, 'category' ));
foreach($ancestors as $ancestor){
$str.='<a href="'. get_category_link($ancestor).'">'. get_cat_name($ancestor). '</a> > ';
}
}
$str.='<a href="'. get_category_link($cat -> term_id). '">'. $cat-> cat_name . '</a> > ';
$str.= ''. $post -> post_title .'';
} elseif(is_page()){
//固定ページ
if($post -> post_parent != 0 ){
$ancestors = array_reverse(get_post_ancestors( $post->ID ));
foreach($ancestors as $ancestor){
$str.='<a href="'. get_permalink($ancestor).'">'. get_the_title($ancestor) .'</a> > ';
}
}
$str.= ''. $post -> post_title .'';
} elseif(is_date()){
if(get_query_var('day') != 0){
$str.='<a href="'. get_year_link(get_query_var('year')). '">' . get_query_var('year'). '年</a> > ';
$str.='<a href="'. get_month_link(get_query_var('year'), get_query_var('monthnum')). '">'. get_query_var('monthnum') .'月</a> > ';
$str.=''. get_query_var('day'). '日';
} elseif(get_query_var('monthnum') != 0){
$str.='<a href="'. get_year_link(get_query_var('year')) .'">'. get_query_var('year') .'年</a> > ';
$str.=''. get_query_var('monthnum'). '月';
} else {
$str.=''. get_query_var('year') .'年';
}
} elseif(is_search()) {
$str.='keyword :'. get_search_query();
} elseif(is_author()){
$str .='author : '. get_the_author_meta('display_name', get_query_var('author')).'';
} elseif(is_tag()){
$str.='tag : '. single_tag_title( '' , false ). '';
} elseif(is_attachment()){
$str.= ''. $post -> post_title .'';
} elseif(is_404()){
$str.='404 Not found';
} else{
$str.=''. wp_title('', true) .'';
}
$str.='
';
}
echo $str;
}
参考サイト
http://bl6.jp/web/wordpress/wp-breadcrumb-list-without-plugin/
※コードはほぼ同一だが、ul、li を除去し、 > とした。
この後、header.php テンプレートファイル内(headerの直下など)に、
<!--?php the_breadcrumb(); ?-->を挿入する。

