ミギムキ

[WordPress] パンくずリストをプラグインなしで設置したい

やりたいこと

サンプルコード

functions.php

function breadcrumb() { global $post; $html =''; if(!is_home() && !is_admin()) { $html .= '<ul class="breadcrumb">'; $html .= '<li><a href="'. home_url() .'">HOME</a></li>'; if(is_category()) { $cat = get_queried_object(); if($cat->parent != 0) { $ancestors = array_reverse( get_ancestors($cat->cat_ID, 'category') ); foreach($ancestors as $ancestor) { $html .= ' <li><a href="'. get_category_link($ancestor) .'">'. get_cat_name($ancestor) .'</a></li>'; } } $html .= ' <li>'. $cat->cat_name . '</li>'; } elseif(is_page()) { if($post->post_parent != 0) { $ancestors = array_reverse( get_post_ancestors($post->ID) ); foreach($ancestors as $ancestor) { $html .= ' <li><a href="'. get_permalink($ancestor) .'">'. get_the_title($ancestor) .'</a></li>'; } } $html .= ' <li>'. get_the_title() .'</li>'; } elseif(is_single()) { $categories = get_the_category($post->ID); $cat = $categories[0]; if($cat != 0) { $ancestors = array_reverse( get_ancestors($cat->cat_ID, 'category') ); foreach($ancestors as $ancestor) { $html .=' <li><a href="'. get_category_link($ancestor) .'">'. get_cat_name($ancestor) .'</a></li>'; } $html .= ' <li><a href="'. get_category_link($cat->term_id) .'">'. $cat->cat_name .'</a></li>'; } $html .= ' <li>'. get_the_title() .'</li>'; } elseif(is_404()) { $html .= ' <li>ページが見つかりませんでした</li>'; } else { // 例外 } $html .= '</ul>'; echo $html; } }

html

<?php breadcrumb(); ?>

CSS

.breadcrumb { display: flex; padding: 1em 0px; list-style: none; } .breadcrumb > li { position: relative; font-size: 14px; } .breadcrumb > li:nth-of-type(n + 2) { padding: 0px 0px 0px 2.5em; } .breadcrumb > li:nth-of-type(n + 2)::before { position: absolute; top: 50%; left: 1em; width: 0.5em; height: 0.5em; transform: translateY(-50%) rotate(45deg); border-right: 2px solid #dedede; border-top: 2px solid #dedede; content: ""; }

仕組み、解説、補足など

ご質問など受け付けています

記事の中でわかりにくかったところ、もっと知りたかったこと、間違っていることなど、何でもお気軽にご連絡ください。

ご連絡は下記フォームを利用いただくか、ツイッターアカウント@flat8migi宛てでもOKです。