get_posts()で取得した記事のカテゴリーとタグを出力する方法

Contents
カテゴリー(リンクなし)の出力
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
//まずはループを作る <?php $my_posts= get_posts(array( 'post_type' => 'blog', 'order' => 'DESC' )); foreach($my_posts as $my_post: //各投稿のカテゴリーを取得 $my_cats = get_the_category($my_post); foreach($my_cats as $my_cat): ?> //カテゴリーを出力 <span><?php echo $my_cat->name; ?></span> <?php endforeach ; endforeach; ?> |
カテゴリー(リンクあり)の出力
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
//(サブループの場合) //まずはループを作る <?php $my_posts= get_posts(array( 'post_type' => 'blog', 'order' => 'DESC' )); foreach($my_posts as $my_post: //カテゴリー(リンクあり)を取得 the_category(); endforeach; ?> //(メインループの場合) //まずはループを作る <?php while (have_posts()) : the_post(); the_category(); endwhile; ?> |
このようにコードを書くと
html
1 2 3 4 5 |
<ul class="post-categories"> <li> <a href="http://nobu-portfolio.com/category/blog/" rel="category tag">ブログ</a> </li> </ul> |
このようにulタグ、liタグ、aタグを出力してくれる。
カテゴリー名とカテゴリーリンクを別々に出す方法
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php $my_posts= get_posts(array( 'post_type' => 'blog', 'order' => 'DESC' )); foreach($my_posts as $my_post: //各投稿のカテゴリーを取得 $my_cats = get_the_category($my_post); foreach($my_cats as $my_cat): ?> //カテゴリーのリンクの出力 <a href="<?php echo get_category_link($my_cat);?> //カテゴリーの出力 <?php echo $my_cat->name; ?> </a> <?php endforeach ; endforeach; ?> |
タグ(リンクなし)の出力
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
//まずはループを作る <?php $my_posts= get_posts(array( 'post_type' => 'blog', 'order' => 'DESC' )); foreach($my_posts as $my_post: //各投稿のタグを取得 $my_tags = get_the_tags($my_post); foreach($my_tags as $my_tag): ?> //タグを出力 <span><?php echo $my_tag->name; ?></span> <?php endforeach ; endforeach; ?> |
タグ名とタグのリンクを別々に出す方法
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php $my_posts= get_posts(array( 'post_type' => 'blog', 'order' => 'DESC' )); foreach($my_posts as $my_post: //各投稿のカテゴリーを取得 $my_tags = get_the_tags($my_post); foreach($my_tags as $my_tag): ?> //カテゴリーのリンクの出力 <a href="<?php echo get_category_link($my_tag);?> //カテゴリーの出力 <?php echo $my_tag->name; ?> </a> <?php endforeach ; endforeach; ?> |
関連記事
get_posts()で取得した記事のタクソノミーを出力する方法