LoginSignup
6
2

More than 3 years have passed since last update.

Breadcrumb NavXTでダミーのパンくずを項目間に足す

Last updated at Posted at 2020-03-14

Wordpress案件で、パンくずにBreadcrumb NavXT使う際、
「アーカイブ(一覧)ページを持たない記事ページで、パンくず的には下層に見せたい」という場合のメモ。

  • 病院のサイトで、「診療案内」の中にある「外科」というページ
    • 診療案内TOPは存在しない
    • 「外科」はカスタム投稿タイプ(service)とする

この場合、アーカイブがないので
HOME > 外科 になるけど
HOME > 診療案内※ > 外科 にしたい。(診療案内はリンクなし)

「アーカイブページを作って、serviceページだったらパンくずの2番目からリンクをはずす」
というやり方も考えたけど、不要なアーカイブページは存在させたくないし、
上記のやり方でもパンくずいじる必要は出てくるので、
ダミーのパンくずを追加する方向で調べた。

参考)特定のパンくずアイテムだったらリンクを消す

https://mtekk.us/archives/guides/remove-the-link-in-a-breadcrumb/

調査

「静的なパンくずを足す」を試したところ、一番左に静的な項目がたされる。

https://mtekk.us/archives/guides/add-a-static-breadcrumb-to-the-breadcrumb-trail/

普段phpほぼ使わないので読解を要する・・

  • パンくず1つ1つ(アイテム)が bcn_breadcrumb というクラス Github
  • それを覆っているのが bcn_breadcrumb_trail というクラス Github

ぽくて、 bcn_breadcrumb_trailadd メソッドで、
静的に追加したい bcn_breadcrumb オブジェクトを配列に追加している様子。
https://github.com/mtekk/Breadcrumb-NavXT/blob/master/class.bcn_breadcrumb_trail.php#L165

GOAL

👉ということは、bcn_breadcrumb_trail の配列の任意の場所(今回は2番目)に、
「診療案内」という bcn_breadcrumb オブジェクトを足せればよい◎

コード

functions.php
/**
 * パンくず
 */
function my_static_breadcrumb_adder( $breadcrumb_trail ) {
    if ( get_post_type() === 'service' ) {
        $item = new bcn_breadcrumb( '診療案内', NULL, array('post') );
        $stuck = array_pop( $breadcrumb_trail->breadcrumbs ); // HOME 一時退避
        $breadcrumb_trail->breadcrumbs[] = $item; //診療案内 追加
        $breadcrumb_trail->breadcrumbs[] = $stuck; //HOME 戻す
    }
}
add_action('bcn_after_fill', 'my_static_breadcrumb_adder');

解説

if ( get_post_type() === 'service' ) {

投稿タイプが一致する場合に

$item = new bcn_breadcrumb( '診療案内', NULL, array('post') );

パンくずアイテムを作る。
bcn_breadcrumb のコンストラクタで引数確認。URLはNULLで。
https://github.com/mtekk/Breadcrumb-NavXT/blob/master/class.bcn_breadcrumb.php#L51

$stuck = array_pop( $breadcrumb_trail->breadcrumbs ); // HOME 一時退避

$breadcrumb_trail->breadcrumbs でパンくずの配列が取得できる。
※この配列、HOME > アイテム1 > アイテム2 とある場合、一番右(アイテム2)が0番目。HOMEが一番最後。
array_popで、HOMEを一度避ける。

$breadcrumb_trail->breadcrumbs[] = $item; //診療案内 追加
$breadcrumb_trail->breadcrumbs[] = $stuck; //HOME 戻す

あとは順番に追加して、

add_action('bcn_after_fill', 'my_static_breadcrumb_adder');

アクションフックで実行
無事、こう HOME > 診療案内 > 外科 なりました。

おわり

phpの配列の扱いでちょっと詰まった。
配列の任意のindex(2番目)に足すんだから、array_spliceでいけそうやな、
って思ったのだけど、エラーで怒られた・・

そもそも
$breadcrumb_trail->breadcrumbs[] = $item;
これでおしりに追加できるっていうのが普段使わない人からするとなんかすごく不慣れだ。。笑
(1回空にして代入します!みたいに思っちゃった)

PHP、もっとちゃんと読めるようになりたいなーと思いました。🐬

6
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2