Display Related Posts in WordPress without a Plugin

Display Related Posts in WordPress without a Plugin

Paste the following code in single.php where you want to display related posts
01<?php
02//for use in the loop, list 5 post titles related to first tag on current post
03$tags = wp_get_post_tags($post->ID);
04if ($tags) {
05echo 'Related Posts';
06$first_tag = $tags[0]->term_id;
07$args=array(
08'tag__in' => array($first_tag),
09'post__not_in' => array($post->ID),
10'posts_per_page'=>5,
11'caller_get_posts'=>1
12);
13$my_query = new WP_Query($args);
14if( $my_query->have_posts() ) {
15while ($my_query->have_posts()) : $my_query->the_post(); ?>
16<a href="<?php the_permalink() ?>" rel="bookmark"title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
17 
18<?php
19endwhile;
20}
21wp_reset_query();
22}
23?>

留言

這個網誌中的熱門文章

How to PHP export to Excel 2

html viewport meta