wordpress强大的功能着实让人喜欢,可以随便的diy,不用插件实现一些常用功能是上上之选,之前网上盛传的不使用插件就能实现的五个常用功能一文中的相关日志函数,不是很完善,加到单篇日志后,下面的评论会变成最后一篇相关日志的评论,大概是loop出了问题。而这段代码不会出现这个弊病,并且在没有相关日志的情况下,会显示随机日志。原函数在没有相关日志时,显示最新文章,修改为显示随机日志。

效果请参见本日志下方的:您可能对这些文章感兴趣

<ul id=”randomposts”>

<?php

$tags = wp_get_post_tags($post->ID);

if ($tags) {

$first_tag = $tags[0]->term_id;

$args=array(

‘tag__in’ => array($first_tag),

‘post__not_in’ => array($post->ID),

’showposts’=>10,

‘caller_get_posts’=>1

);

$my_query = new WP_Query($args);

if( $my_query->have_posts() ) {

echo ‘<h3>相关日志</h3>’;

while ($my_query->have_posts()) : $my_query->the_post(); ?>

<li><?php the_time(‘Y年m月d日’) ?> — <a href=”<?php the_permalink() ?>” rel=”bookmark” title=”查看>> <?php the_title_attribute(); ?>”><?php the_title(); ?> <?php comments_number(‘ ‘,’(1)’,'(%)’); ?></a> </li>

<?php

endwhile;

}else{

echo ‘<h3>随机日志</h3>’;

$posts = get_posts(‘numberposts=10&orderby=rand’);

foreach($posts as $post) {

setup_postdata($post);

echo ‘<li>’;

the_time(‘Y年m月d日’);

echo ‘ — <a href=”‘ . get_permalink() . ‘”>’ . get_the_title() . ‘</a></li>’;

}

$post = $posts[0];

}

wp_reset_query();

}

?>

</ul>

 打开你皮肤文件夹下的style.css,加入以下样式的代码即可:

#randomposts h3{color:#F60;margin-left:5px;padding:5px 0}

#randomposts li{list-style:circle;margin:0 0 7px 40px;font-size:12px}