Learning site for website creation

33:投稿詳細に同じカテゴリ・タグの最新投稿一覧を表示する

公開日:2018年11月07日

投稿詳細ページに同じカテゴリの投稿一覧と同じタグの最新投稿一覧を表示させます。

single.php

<?php get_header(); ?>

  <div class="content">
    <div class="main">

      <div class="main-loop">
        <div class="inner">
<?php /***** メインループ開始 *****/ ?>
<?php if (have_posts()) :?>
<?php while (have_posts()) : the_post(); ?>
<?php $id = get_the_ID(); ?>
<?php // テンプレートパーツ読み込み:一覧 ?>
<?php get_template_part('content','single'); ?>
<?php endwhile; ?>
<?php else: ?>
<?php // テンプレートパーツ読み込み:記事なし ?>
<?php get_template_part('content','none'); ?>
<?php endif; ?>
<?php /***** メインループ終了 *****/ ?>

<?php // 前後記事リンク ?>
          <div class="pagination-single">
            <p class="prev"><?php previous_post_link('%link'); ?></p>
            <p class="next"><?php next_post_link('%link'); ?></p>
          </div>

        </div><!-- /.inner -->
      </div><!-- /.main-loop -->

<?php /***** サブループ条件 *****/ ?>
<?php // 同じカテゴリの記事 ?>
<?php
$catList = get_the_category();
for ($i=0; $i < count($catList); $i++) {
  $catName = $catList[$i]->name;
  $args = array(
    'post_type' => 'post',
    'posts_per_page' => 5,
    'category_name' => $catName,
    'orderby' => 'date',
    'order' => 'DESC',
    'post__not_in' => array($id),
  );
  echo getSubloop($args, '関連カテゴリ:'.$catName);
}
?>


<?php /***** サブループ条件 *****/ ?>
<?php // 同じタグの記事 ?>
<?php
if (has_tag()) {
  $tagList = get_the_tags();
  for ($i=0; $i < count($tagList); $i++) {
    $tagName = $tagList[$i]->name;
    $tagSlug = $tagList[$i]->slug;
    $args = array(
      'post_type' => 'post',
      'posts_per_page' => 5,
      'tag' => $tagSlug,
      'orderby' => 'date',
      'order' => 'DESC',
      'post__not_in' => array($id),
    );
    echo getSubloop($args, '関連タグ:'.$tagName);
  }
}
?>

    </div><!-- /.main -->
    <?php get_sidebar(); ?>
  </div><!-- /.content -->

<?php
get_footer();

このページで出てくる関数

WordPress関数は「公式サイトのドキュメント」で確認しましょう。

WordPress関数

get_header()

have_posts()

the_post()

get_the_ID()

get_template_part()

previous_post_link()

next_post_link()

get_sidebar()

get_footer()

オリジナル関数

getThumbnail()

getCatLinkList()

getTagLinkList()

 

欠席者対応:wireframe12

同じタグのコンテンツ