WordPRESS カテゴリー テンプレタグ
single.php
◯記事が属するカテゴリーIDを取得
<?php if(has_category() ) {
$cats = get_the_category();
$catkwds = array();
foreach($cats as $cat) {
$catkwds = $cat->term_id;
}
} ?>
/* get_the_category()で表示中の記事が属するカテゴリーに関するデータを取得し、IDを取り出して、$catkwdsに代入する。記事が複数の場合カテゴリーに属している場合は、すべてのカテゴリーIDが代入される。*/
<?php
$myposts = get_posts(array(
'post_type' => 'post',
'posts_pre_page' => '6',
'post__not_in' => array($post->ID), #表示中の記事は出力対象から除外するため、気記事のID($post->ID)を指定している。
'category__in' => ' $catkwds', # 上で取得したカテゴリーに属する記事のみを出力対象とするため、category__inパラメーターを$catkwdsにする。
'orderby' => 'asc'
));
if ($myposts) : ?>
<aside class="mymenu">
<h2>記事</h2>
<ul>
<?php foreach($myposts as $post) :
setup_postdata($post); ?>
<li><a href="<?php the_permalink(); ?>">
<div class="thumb" style="background-image:url(<?php echo mythumb('thumbnail);
?>)">
</div>
<div class="text">
<?php the_title(); ?>
</div>
</a>
</li>
<?php endforeach; ?>
</ul>
</aside>
<?php wp_reset_postdata(); endif(); ?>
</article>
<?php endwhile; endif; ?>
</div>