サポート » 使い方全般 » 子カテゴリの表示について

  • 解決済 lau87

    (@lau87)


    投稿記事に子カテゴリのみを表示させたく、
    現状下記コードで出力しているのですが

    <?php
    $cats = get_the_category();
    $current_cat = '';
    foreach ( $cats as $cat ) {
      if ( ! $current_cat || cat_is_ancestor_of( $current_cat, $cat ) ) {
        $current_cat = $cat;
      }
    }
    ?>
    <div class="<?php echo "$current_cat->category_nicename"; ?>">
      <?php
        $cats = get_the_category();
        foreach($cats as $cat):
        if($cat->parent) echo $cat->cat_name;
        endforeach;
      ?>
    </div>

    これですと小カテゴリがない場合、空のDIVタグ<div class=””></div>が出力されてしまいます。
    ifなどの条件分岐で子カテゴリがある場合のみ出力し、
    ない場合は何も出力しないことは可能でしょうか?

2件の返信を表示中 - 1 - 2件目 (全2件中)
  • gblsm

    (@gblsm)

    これでどうでしょう。
    動作を検証していないので間違いがあるかもしれませんが…

    <?php
    $cats = get_the_category();
    $current_cat = '';
    $child_cats = array();  // 後で表示するカテゴリーの配列
    foreach ( $cats as $cat ) {
      if ( ! $current_cat || cat_is_ancestor_of( $current_cat, $cat ) ) {
        $current_cat = $cat;
      }
      if($cat->parent) $child_cats[] = $cat;    // 子カテゴリーなら配列へ入れる
    }
    if ( $child_cats ) :    // 子カテゴリーがある時だけ
    ?>
    <div class="<?php echo "$current_cat->category_nicename"; ?>">
      <?php
        foreach ( $child_cats as $cat ) :
          echo $cat->cat_name;  // 子カテゴリーであることを確認済みなので無条件に表示
        endforeach;
      ?>
    </div>
    <? endif; ?>

    トピック投稿者 lau87

    (@lau87)

    >gblsm様

    ご返事ありがとうございます。
    無事に空のDIVが出力されずに出来ました。
    これにて解決済みとさせていただきます。

2件の返信を表示中 - 1 - 2件目 (全2件中)
  • トピック「子カテゴリの表示について」には新たに返信することはできません。