在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; ?>
