サポート » 使い方全般 » タームのリンクの取得について

  • 望んでいる結果は得られているのですが、これは違うだろうな…と思っているので質問させて下さい。
    関数リファレンス/get the terms

    このページを見て、各記事が持っているタームの情報を取得しています。
    2箇所、それぞれ表示したいcssが違うため、見た感じからして無理矢理感がありますが、下記のように書いています。

    front-page.php用

    function custom_taxonomies_term_link(){
      $post = get_post( $post->ID );
      $post_type = $post->post_type;
      $taxonomies = get_object_taxonomies( $post_type, 'objects' );
      $out = array();
      foreach ( $taxonomies as $taxonomy_slug => $taxonomy ){
        $terms = get_the_terms( $post->ID, $taxonomy_slug );
        if ( !empty( $terms ) ) {
          $out[] = "";
          foreach ( $terms as $term ) {
            $out[0] =
            '<span class="cat tc catdef '
            . $term->slug
            . '"><a href="'
            . get_term_link( $term->slug, $taxonomy_slug ) .'">'
            . $term->name
            . "</a></span>";
          }
          $out[] = "";
        }
      }
      return implode('', $out );
    }

    archive.php用

    function custom_taxonomies_terms_links(){
      $post = get_post( $post->ID );
      $post_type = $post->post_type;
      $taxonomies = get_object_taxonomies( $post_type, 'objects' );
      $out = array();
      foreach ( $taxonomies as $taxonomy_slug => $taxonomy ){
        $terms = get_the_terms( $post->ID, $taxonomy_slug );
        if ( !empty( $terms ) ) {
          $out[] = "";
          foreach ( $terms as $term ) {
            $out[] =
            '<span class="ichiran-cat tr '
            . $term->slug
            . '"><a href="'
            . get_term_link( $term->slug, $taxonomy_slug ) .'">['
            . $term->name
            . "]</a></span>";
          }
          $out[] = "";
        }
      }
      return implode('', $out );
    }

    front-page.phpには、複数タームがあるなかの、1つだけ表示させたかったので、

    $out[0] =

    とゼロを放り込んでみたのですが…間違ってるだろうな…と。
    出力側の

    <?php echo custom_taxonomies_terms_links(); ?>

    に、通常カテゴリーを1つだけ表示させる、

    <?php $cat = get_the_category(); $cat = $cat[0]; { echo '<a href="' . get_category_link($cat->term_id) . '" title="'. esc_attr($cat->name) . '">' . $cat->cat_name . '</a>'; } ?>

    のようにかければ、functions.phpに書くのは1つで済むのになぁとまでは考えているのですが…。

    どうぞよろしくお願いいたします!

1件の返信を表示中 - 1 - 1件目 (全1件中)
  • モデレーター jim912

    (@jim912)

    front-page.phpには、複数タームがあるなかの、1つだけ表示させたかったので、

    $out[0] =

    とゼロを放り込んでみたのですが…間違ってるだろうな…と。

    このコードだと、取得した複数タームのうち最後のタームが採用されます。理由はおわかりになるでしょうか。

    通常カテゴリーを1つだけ表示させる、

    <?php $cat = get_the_category(); $cat = $cat[0]; { echo '<a href="' . get_category_link($cat->term_id) . '" title="'. esc_attr($cat->name) . '">' . $cat->cat_name . '</a>'; } ?>

    のようにかければ、functions.phpに書くのは1つで済むのになぁとまでは考えているのですが…。

    いくつか方法は考えられると思います。

    • 関数内で条件分岐タグを使って、分岐処理させる
    • 関数の引数によって、class の属性値、出力数を変化させる

    なお、関数冒頭にある

    $post = get_post( $post->ID );

    において、$post->ID は取得できていないはずですので、引数を指定する必要はありません。

1件の返信を表示中 - 1 - 1件目 (全1件中)
  • トピック「タームのリンクの取得について」には新たに返信することはできません。