ASITIS

ブログ用のメモブログ

WordPressパンくずリストをプラグインなしで実装する方法

WordPressプラグインを使用せずにパンくずリストをfunction.phpから呼び出して使用する方法です。とってもシンプルに作っています。

/*
 * パンくずリスト
 */
function the__breadcrumb( $before = '', $after = '' ){
  global $post;
$str = function( $link, $title ) { $sepa = ' / '; // ホーム echo '<li itemscope="itemscope" itemtype="http://data-vocabulary.org/Breadcrumb">'; echo '<a href="'.$link.'" itemprop="url">'; echo '<span itemprop="title">'.$title.'</span>'; echo '</a>'.( is_main_site() && is_front_page() ? '' : $sepa ); echo '</li>'; }; echo $before; echo '<ol class="breadcrumb">'; $str( get_home_url( '/' ), get_bloginfo( 'name' ) . ' - TOP' ); // 固定ページ if ( is_page() && $post->post_parent != 0 ) { $ancestors = array_reverse( get_ancestors( $post->ID, 'page' ) ); foreach( $ancestors as $ancestor ) { $str( get_permalink( $ancestor ), get_the_title( $ancestor ) ); } // 投稿ページ } elseif ( is_single() ) { $cat = get_the_category( $post->ID ); if ( isset( $cat, $cat[0] ) ) { $cat = $cat[0]; // 親カテゴリがある場合は親のカテゴリを追加 if ( $cat->parent!=0 ): $ancestors = array_reverse( get_ancestors( $cat->cat_ID, 'category' ) ); foreach( $ancestors as $ancestor ): $str( get_category_link( $ancestor ), get_the_category_by_ID( $ancestor ) ); endforeach; endif; // カテゴリ名 $str( get_category_link( $cat->cat_ID ), get_the_category_by_ID( $cat->cat_ID ) ); } // カテゴリページ } elseif ( is_category() ) { $cat = get_queried_object(); if ( $cat->parent!=0 ) { $ancestors = array_reverse( get_ancestors( $cat->cat_ID , 'category' ) ); foreach( $ancestors as $ancestor ) { $str( get_permalink( $ancestor ), get_the_title( $ancestor ) ); } } } // 検索ページでキーワードが入力されてない場合 if ( is_search() && !get_search_query() ) { echo '<li>'.'検索結果'.'</li>'; // 現在のページ } else { echo '<li>'.wp_get_document_title().'</li>'; } echo '</ol>'; echo $after; }

下記で実行

if ( function_exists( 'the__breadcrumb' ) ) { the__breadcrumb( '', '' ); }
wp_get_document_title();

の サイト名を消したい場合は

add_filter( 'document_title_parts', 'remove_title_sitename' );
  function remove_title_sitename( $title ) {
    unset( $title['site'] );
    if ( is_front_page() ) {
      unset( $title['title'] );
    } else {
      unset( $title['tagline'] );
    }
    return $title;
  }