
タームを取得するときもいつも調べちゃうよねw
目次
get_terms
get_termsで何ができる?
指定されたタクソノミーに含まれるタームをすべて取得するのが、get_terms
<?php get_terms($taxonomies, $args ); ?>$taxonomies 必須 タームを取得するタクソノミー。 複数なら配列arrayで。
$args 戻り値の条件など指定するパラメーター。指定できる引数はこちらを参照
どんなときに使う?【サンプル】
タームごとにそれに紐付く記事一覧を出力するとき等。
【具体例】
店舗情報をカスタム投稿(post type = ‘shop’)で管理。カスタムタクソノミー(taxonomy = ‘prefecture’)で都道府県の情報を付与。店舗情報を都道府県ごとに出力する。
get_termsでカスタム投稿’shop’に紐付く全タームを取得して、foreachで各タームごとに該当する記事を出力する。
<?php
  $tax_name = 'prefecture'; /*タクソノミースラッグ*/
  $posttype_name = 'shop'; /*カスタム投稿タイプ名*/
  $terms = get_terms($tax_name);
  foreach ( $terms as $term ):
    $args = array(
      'post_type' => $posttype_name,
      'tax_query' => array(
        array(
          'taxonomy' => $tax_name,
          'field'    => 'slug',
          'terms'    => $term->slug,
        ),
      ),
    );
    $the_query = new WP_Query( $args );
?>
<!-- ターム名の表示 start -->
 <h2><?php echo $term->name ?></h2>
<!-- ターム名の表示 end -->
 <?php if ($the_query->have_posts()): ?>
  <ul>
  <?php while ($the_query->have_posts()) : $the_query->the_post(); ?>
<!-- 記事表示 start -->
   <li><a href="<?php echo get_permalink() ?>"><?php the_title() ?></a></li>
<!-- 記事表示 end -->
  <?php endwhile; ?>
  </ul>
 <?php endif; ?>
<?php endforeach; wp_reset_postdata(); ?>get_the_terms
get_the_termsで何ができる?
投稿に割り当てられたタームを取得するのが、get_the_terms
<?php get_the_terms( $id, $taxonomy ); ?>$id 必須 投稿 ID
$taxonomy 必須 タームを取得するタクソノミーの名前。
どんなときに使う?【サンプル】
投稿に紐ついてるタームをタグ状に全て出力するようなとき等。
【具体例】
カスタム投稿(’news’)の記事に紐付くキーワード(taxnomy = ‘keyword’)タグのように出力する。ループ内においてget_the_termsで記事に紐付く全タームを取得し、foreachで一つずつ出力する。
<?php
$tax_name = 'keyword'; /*タクソノミースラッグ*/
$terms = get_the_terms($post->ID, $tax_name);
foreach( $terms as $term ) : ?>
<a href="<?php ecno get_term_link($term->slug, $tax_name); ?>" ?><?php echo $term->name; ?></a>
<?php endforeach; ?>まとめ
get_terms はターム全部取得、get_the_terms は特定の記事に紐付くターム全部取得。
「get_categories と get_the_categories」、「get_tags と get_the_tags」の関係も同じです。



まとめて覚えてスッキリ〜♪




