投稿記事に関連する記事も表示させたい【WPハック】
WordPressにはイロイロとプラグインが揃っていて、簡単に機能拡張が出来て便利ですが、
プラグインによっては余計な機能やコードが入ってしまい、ちょっと重くなってしまいます。
ちょっとしたことなら、プラグインを使わずにやってしまった方がいいんじゃね?と思うわけですよ。KRUZ的に。
なので、関連する記事を表示するコード を紹介です。
このコードは、投稿されたポストにタグで関連付けしていて、まぁ超簡単に実装しちゃいましょう。という建前の手抜きですww。
実装は簡単です。関連記事と表示させたいテンプレート(ほとんどの場合、single.phpじゃないでしょうか?)に、下記コードを書きます。
おっと、必ずループ内に書いてね。
<?php
// list 5 post titles related to first tag on current post
$tags = wp_get_post_tags($post->ID);
if ($tags) {
echo '以下の記事が関連がありそうです。';
$first_tag = $tags[0]->term_id;
$args=array(
'tag__in' => array($first_tag),
'post__not_in' => array($post->ID),
'showposts'=>5,
'caller_get_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) { while ($my_query->have_posts()) : $my_query->the_post(); ?>
<p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
<?php
endwhile;
}
}
?>
ね?たったコレだけのコードで無理にプラグイン入れなくても、とりあえずは実現できるでしょ?
もっと高機能なものは欲しいとかなら、プラグインいれたほうがいいよ。
ネタ元:WpRecipes
2010/02/21 追記
ループ処理によっては、不具合がありました。
記事にコメントがあった場合、関連記事にそのコメントがポストされたように見えます。
DBとか見てもちゃんと記事にコメントされているのに、WP上では関連記事にコメントが表示されます。
もしかして!と思い、コードを削除したらちゃんとポストされた記事にコメントされました。要修正です。2010/02/22 追記
問題のコード修正しました。修正版は「投稿記事に関する記事も表示させたい。解決編?」で公開しています。
Facebook comments:
Leave a Reply
※コメントが認証されるまで、コメントは反映されません。


14 Responses so far.
A cute site. Thanks for sharing it with me!
Thank you. Good luck can provide good information to be posted.
These are new ideas.
Thank you for comment. Only useful? is nice.
Thanks for this excellent read. I liked every little bit of it. I bookmarked this and will be reading again.
Thank you. Very honored
I really like your point of view. Very good post. Thank God to discover all the information. Cheers
I impressed reading your article . Keep the good job but Ill be in touch. Lookin’ forward
So helpful and so useful post. Thanks for such informative post. Good job.
Important information for me. Thanks for really competent informative article. Ill be in touch with U
Im happy U did it. Thanks for writing so informative post. Im lookin’ forward to c and read ur next post. Cheers
Really helpful information for me. Thnak U much times as think as possible. Luv U
That is f*ckin’ awesome . Very good and interesting article. Thanks for helpful and useful information.