顯示相關文章程式碼 – Related Posts

WordPress討論區看到一則討論,提到利用tags的歸類方式顯示相關文章,只需要在檔案中加入一段程式碼就可以,對於不喜歡加裝外掛程式的朋友或是對WordPress程式有興趣的朋友都可以參考看看。

在想要顯示相關文章的地方加入以下的程式碼:

<?php
//for use in the loop, list 5 post titles related to first tag on current post
$tags = wp_get_post_tags($post->ID);
if ($tags) {
  echo 'Related Posts';
  $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(); ?>
      <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
 
      <?php
    endwhile;
  }
wp_reset_query();
}
?>

以上程式碼必須加在 The Loop 之間。

The Loop 通常如下開始:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

The Loop 結束通常如下:

<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>

另外,skyfate也寫過一篇關於同分類文章的程式教學,有興趣的朋友也可以去參考看看。

This entry was posted in 網誌 and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">