WordPressで同一カテゴリの記事を関連記事として表示したいときがあります。
そんなときは、次のようにget_the_category(get_the_id())として、エントリのカテゴリ一覧を取得してからいろいろな処理をします。get_the_id()が使えないときは、$wp_queryを使います。「$cur_post=$wp_query->get_queried_object(); get_the_category($cur_post->ID);」としてあげれば良いでしょう。細かい処理については、実際のコードを見た方がわかるでしょう。
<?php
$post_cats = get_the_category(get_the_id());
foreach ($post_cats as $post_cat) :
echo "同じカテゴリの記事: ";
?>
<a href="<?php echo get_category_link($post_cat->term_id); ?>"><?php echo $post_cat->name; ?></a><br />
<ul>
<?php
$same_cat_posts = get_posts("posts_per_page=5&offset=1&category=" . $post_cat->term_id);
foreach ($same_cat_posts as $post) :
echo '<li><a href="' . get_permalink($post -> ID) . '">' . $post->post_title . "</a></li>";
endforeach;
?>
</ul>
<?php
endforeach;
?>
$post_cats = get_the_category(get_the_id());
foreach ($post_cats as $post_cat) :
echo "同じカテゴリの記事: ";
?>
<a href="<?php echo get_category_link($post_cat->term_id); ?>"><?php echo $post_cat->name; ?></a><br />
<ul>
<?php
$same_cat_posts = get_posts("posts_per_page=5&offset=1&category=" . $post_cat->term_id);
foreach ($same_cat_posts as $post) :
echo '<li><a href="' . get_permalink($post -> ID) . '">' . $post->post_title . "</a></li>";
endforeach;
?>
</ul>
<?php
endforeach;
?>
ちなみに、setup_postdata()を使う方法もあります。こちらを使うと、the_permalink() とか the_title() といった関数が使えるようになります。むやみに使うと、同一ページ内の他の所への影響がでますから、そこでsetup_postdata()しても良いかを考えた上で、利用する必要があります。
<?php
$post_cats = get_the_category(get_the_id());
foreach ($post_cats as $post_cat) :
echo "同じカテゴリの記事: ";
?>
<a href="<?php echo get_category_link($post_cat->term_id); ?>"><?php echo $post_cat->name; ?></a><br />
<ul>
<?php
$same_cat_posts = get_posts("posts_per_page=5&offset=1&category=" . $post_cat->term_id);
foreach ($same_cat_posts as $post) :
setup_postdata($post);
echo '<li><a href="' . the_permalink() . '">' . the_title() . '</a></li>';
endforeach;
?>
</ul>
<?php
endforeach;
?>
$post_cats = get_the_category(get_the_id());
foreach ($post_cats as $post_cat) :
echo "同じカテゴリの記事: ";
?>
<a href="<?php echo get_category_link($post_cat->term_id); ?>"><?php echo $post_cat->name; ?></a><br />
<ul>
<?php
$same_cat_posts = get_posts("posts_per_page=5&offset=1&category=" . $post_cat->term_id);
foreach ($same_cat_posts as $post) :
setup_postdata($post);
echo '<li><a href="' . the_permalink() . '">' . the_title() . '</a></li>';
endforeach;
?>
</ul>
<?php
endforeach;
?>