notebook

備忘録

single(投稿個別ページ)ターム名を表示する

2025.07.07

PHP記述

<!-- / ホームリンク -->
<?php echo esc_url(home_url('/')); ?>


<!-- / カスタム投稿タイプのターム名を表示 -->
<?php
$terms = get_the_terms($post->ID, 'タクソノミースラッグ');
if (!empty($terms)) {
    foreach ($terms as $term):
        echo $term->name;
    endforeach;
    //記事がタームに登録されている場合の処理
} else {
    echo '未分類';
    //記事がタームに登録されていない場合の処理
}
?>


<!-- / get_the_termsで記事のタームを取得する -->
<?php
// get_the_termsは、その記事が登録されているタクソノミーのターム情報を取得するための関数です。
// 以下のような情報を取得することができます。
$terms = get_the_terms($post->ID, 'タクソノミースラッグ');
foreach ($terms as $term) {
    echo $term->term_id; // タームID
    echo $term->name; // タームの名前
    echo $term->slug; // タームスラッグ
    echo $term->term_group; // 親タームのタームID(↓の'parent'としても格納される)
    echo $term->term_taxonomy_id; // タームが属するタクソノミーのID
    echo $term->taxonomy; // タームが属するタクソノミーの名前
    echo $term->description; // タクソノミーの説明
    echo $term->parent; // 親タームのタームID(↑の'term_group'としても格納される)
    echo $term->count; // このタームが使われている回数
}
?>

カスタム投稿タイプ投稿個別ページ(single-blog.php)
使用例:パンくず

<nav id="nav" itemscope itemtype="http://schema.org/BreadcrumbList">
    <ul id="ul">
        <li class="li" itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">
            <a itemprop="item" href="<?php echo esc_url(home_url('/')); ?>" title="ホーム">
                <abbr itemprop="name" title="ホーム">ホーム</abbr></a>
            <meta itemprop="position" content="1">
        </li>
        <!-- /li -->
        <li class="li" itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">
            <a itemprop="item" href="/blog/" title="備忘録">
                <abbr itemprop="name" title="備忘録">備忘録</abbr></a>
            <meta itemprop="position" content="2">
        </li>
        <!-- /li -->
        <li class="li" itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">
            <h1 itemprop="name" title="<?php
                                        $terms = get_the_terms($post->ID, 'blog_list'); //タクソノミースラッグ
                                        if (!empty($terms)) {
                                            foreach ($terms as $term):
                                                echo $term->name;
                                            endforeach;
                                        } else {
                                            echo '未分類';
                                        }
                                        ?>"></h1>
            <meta itemprop="position" content="3">
        </li>
        <!-- /li -->
    </ul>
    <!-- /ul -->
</nav>
<!-- /nav -->