BreadcrumbList(パンくずリスト)の不具合

Markup (JSON-LD) structured in schema.orgプラグインのサポートフォーラム宛に以下のような書き込みが…

breadcrumb homepage showing 2 items instead of one

The homepage breadcrumb has 2 list-items instead of one.
Position 1 -> blogtitle
Position 2 -> home

Every other page is correct:
Position 1 -> blogtitle
Position 2 -> page
Position 3 -> subpage

How do I get homepage to show only 1 item:
Position 1 -> blogtitle

どうやらパンくずリストの先頭表示が重複する的な話らしく、最初は「(・_・?」っとなってふと思った。「あ!フロントページを固定ページにしている場合の考慮がパンくずリストにない!」と気付く。そうか、パンくずリストの先頭を表示/非表示切り替えられるようにしているけど、非表示時でもフロントページが固定ページの場合、is_page()のif文分岐にひっかかるのか。原因はわかったので改修することに。

フロントページに設定した固定ページ情報取得

パンくずリストの先頭表示/非表示は機能としてそのまま残すとして、パンくずの先頭を表示する際に、フロントページに設定した固定ページの情報を取得してそのタイトルを設定したい。

get_option( ‘show_on_front’ ): returns either ‘posts’ or ‘page’
get_option( ‘page_on_front’ ): returns the ID of the static page assigned to the front page
WordPress.org: Reference / Functions / is_home()

フロントページに固定ページを設定しているかの判定をget_option( 'show_on_front' )で行います。「page」が返ってくれば設定しているということになります。

page判定が返ってきたら、get_option( 'page_on_front' )でフロントページに設定した固定ページのIDを取得します。このIDを引数にget_post()関数をコールします。デフォルトでオブジェクトの形式で値が返ってきます。IDは後の記述で使用するので変数に格納して使用します。

$item_array = array();
$current_url = esc_url( home_url() . $_SERVER['REQUEST_URI'] );

if ( get_option( 'show_on_front' ) == 'page' ) {
	$front_page_id = get_option( 'page_on_front' );
} else {
	$front_page_id = null;
}

if ( isset( $options['home_on'] ) && $options['home_on'] === 'on' ) {
	if ( isset( $options['home_name'] ) && $options['home_name'] !== '' ) {
		$item_array[] = $this->set_schema_breadcrumb_item( home_url(), $options['home_name'] );
	} else {
		if ( is_null( $front_page_id ) ) {
			$item_array[] = $this->set_schema_breadcrumb_item( home_url(), get_bloginfo( 'name' ) );
		} else {
			$front_page   = get_post( $front_page_id );
			$item_array[] = $this->set_schema_breadcrumb_item( home_url(), esc_html( $front_page->post_title ) );
		}
	}
}

$option[]配列は、管理メニューで設定したBreadcrumbListの値です。$options['home_on']が先頭表示判定、$options['home_name']が任意で表示することができる文字列になります。

Schema.org BreadcrumbList Type settings.

4〜8行目でフロントページ設定の判定と設定がpage(True)時にIDを取得しています。17・18行目でget_postで取得した情報を元にパンくずリストの表示を固定ページのタイトルに設定しています。これで先頭の表示はOK。

is_page()の分岐処理を修正

先頭表示はOKなのですが、is_page()関数の判定がこの処理のあとにあります。フロントページに固定ページを設定していても固定ページであることには変わらないので、is_page()関数でのif文分岐で当然trueになり、先頭と固定ページロジックを通って2重に表示されてしまいます。
そこで先程変数に保存しておいたIDで判定します。固定ページのIDがフロントページに設定した固定ページのIDと一致しない場合は表示するという判定をいれます。

・・・
} elseif ( is_page() && $front_page_id != $post->ID ) {
	if( $post->post_parent !== 0 ) {
		$ancestors = array_reverse( get_post_ancestors( $post->ID ) );
		foreach( $ancestors as $ancestor ){
			$item_array[] = $this->set_schema_breadcrumb_item( get_permalink( $ancestor ), get_the_title( $ancestor ) );
		}
	}
	$item_array[] = $this->set_schema_breadcrumb_item( $current_url, $post->post_title );
・・・

2行目に判定を入れました。これで無事対応完了です。Markup (JSON-LD) structured in schema.orgプラグインのバージョン3.2.4としてリリースしました。