サポート » 使い方全般 » get_the_category()について

  • 解決済 roses

    (@roses)


    運営サイトで親カテゴリーに子カテゴリーA・Bのカテゴリー名とその記事一覧を下記のような記述で表示しているのですが、H3見出しのカテゴリー名だけ子カテゴリーA・Bが逆に表示されてしまいます。

    これを子カテゴリーAのH3見出しには子カテゴリーAのカテゴリー名を、子カテゴリーBには子カテゴリーBのカテゴリー名を表示させるにはどうのように修正したらよいのでしょうか?

    <?php
    //子カテゴリーAの一覧
    $posts = get_posts('category=2 & numberposts=5'); ?>
    <h3><?php foreach((get_the_category()) as $cat) { echo $cat->cat_name; } ?></h3>
    <?php if($posts): foreach($posts as $post): setup_postdata($post); ?>
    <p><?php the_time('Y年m月d日'); ?><br />
    <a href="<?php the_permalink(); ?>" title="<?php the_title();?>の詳細はこちら"><?php the_title();?></a></p>
    <?php endforeach; endif ?>
    
    <?php
    //子カテゴリーBの一覧
    $posts = get_posts('category=3 & numberposts=5'); ?>
    <h3><?php foreach((get_the_category()) as $cat) { echo $cat->cat_name; } ?></h3>
    <?php if($posts): foreach($posts as $post): setup_postdata($post); ?>
    <p><?php the_time('Y年m月d日'); ?><br />
    <a href="<?php the_permalink(); ?>" title="<?php the_title();?>の詳細はこちら"><?php the_title();?></a></p>
    <?php endforeach; endif ?>

    ご教授よろしくお願いいたします。

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

    (@jim912)

    rosesさん、こんにちは。

    カテゴリーのIDが分かっているので、get_the_category()ではなく、get_cat_name()かget_the_category_by_ID()を使うのが良いかと思います。(両者の違いは、指定されたカテゴリーが存在しなかった場合の返値です。)

    コードは下記のようになります。

    <h3><?php echo get_cat_name( 2 ) ?></h3>
    トピック投稿者 roses

    (@roses)

    jim912様

    こんにちは。早速のご回答ありがとうございます。
    お教えいただいたget_cat_name()で表示できました。

    私はもっとPHPの関数を勉強しないとダメですね(汗
    前回に引き続きアドバイスありがとうございました:)

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