前几天“不能吧”博主问我要一个关于在WordPress博客中实现无插件的相关文章代码,这段代码其实很简单(我不记得是从哪里获得的,如有谁清楚,请提供作者信息):
<?php $backup = $post; $tags = wp_get_post_tags($post->ID); $tagIDs = array(); if ($tags) { echo '<h3>相关日志</h3>'; echo '<ul>'; $tagcount = count($tags); for ($i = 0; $i < $tagcount; $i++) { $tagIDs[$i] = $tags[$i]->term_id; } $args=array( 'tag__in' => $tagIDs, '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(); ?> <li><a href="<?php the_permalink() ?>" rel="bookmark" title=”<?php the_title(); ?>”><?php the_title(); ?></a></li> <?php endwhile; echo '</ul>'; } else { ?> <ul> <?php query_posts(array('orderby' => 'rand', 'showposts' => 5)); //如果无相关日志,即提供随机日志,数量5可以更改; if (have_posts()) : while (have_posts()) : the_post();?> <li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a></li> <?php endwhile;endif; ?> </ul> <?php } } $post = $backup; wp_reset_query(); ?> 将这段代码贴到想要显示相关日志的地方,即可实现有相关日志显示相关日志,无相关日志显示随机日志的目的。我是放在主题文件(默认的2012主题)content.php 中的下列语句后:
...