很多玩WordPress的朋友喜欢用插件来实现wordpress 随机文章,随机日志,最新文章,最新评论,其实直接用WordPress的代码函数来实现wordpress 随机文章,随机日志,最新文章,最新评论,也是十分简单的,所以没必要用插件,填上随机文章和最新文章后能够大大增加文章的内链。
1.随机文章
使用 WordPress 默认函数 get_posts 中的 orderby=rand 属性来随机选取文章链接。多篇文章并以列表形式展示,则代码如下:
<h4>随机文章</h4>
<?php $rand_post = get_posts(‘numberposts=10&orderby=rand’);
foreach( $rand_post as $post ) : ?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
以上代码随机选择 10 篇文章,列表样式可以根据需要自定义。
另一个版本 ,用query_posts生成随机文章列表。
<?php
query_posts(array(‘orderby’ => ‘rand’, ‘showposts’ => 2));
if (have_posts()) :
while (have_posts()) : the_post();?>
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a> <?php comments_number(”, ‘(1)’, ‘(%)’); ?><br />
<?php endwhile;endif; ?>
如果你还想显示含有标题和文章摘要的随机文章,可以这样写
<?php
query_posts(array(‘orderby’ => ‘rand’, ‘showposts’ => 1));
if (have_posts()) :
while (have_posts()) : the_post();
the_title(); //这行去掉就不显示标题,你当然不会这么做
the_excerpt(); //去掉这个就不显示摘要了
endwhile;
endif; ?>
2. 最新文章
WordPress最新文章的调用可以使用一行很简单的模板标签wp_get_archvies来实现. 代码如下:
<?php get_archives(‘postbypost’, 10); ?>
(显示10篇最新更新文章)或
<?php wp_get_archives(‘type=postbypost&limit=20&format=custom’); ?>
后面这个代码显示你博客中最新的20篇文章,其中format=custom这里主要用来自定义这份文章列表的显示样式。具体的参数和使用方法你可以参考官方的使用说明- wp_get_archvies。(fromat=custom也可以不要,默认以UL列表显示文章标题。)
补充: 通过WP的query_posts()函数也能调用最新文章列表, 虽然代码会比较多一点,但可以更好的控制Loop的显示,比如你可以设置是否显示摘要。具体的使用方法也可以查看官方的说明。
3. 最新留言,最新评论
下面是我之前在一个WordPress主题中代到的最新留言代码,具体也记不得是哪个主题了。该代码直接调用数据库显示一份最新留言。其中LIMIT 10限制留言显示数量。绿色部份则是每条留言的输出样式。
<?php
global $wpdb;
$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID,
comment_post_ID, comment_author, comment_date_gmt, comment_approved,
comment_type,comment_author_url,
SUBSTRING(comment_content,1,30) AS com_excerpt
FROM $wpdb->comments
LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID =
$wpdb->posts.ID)
WHERE comment_approved = ‘1’ AND comment_type = ” AND
post_password = ”
ORDER BY comment_date_gmt DESC
LIMIT 10";
$comments = $wpdb->get_results($sql);
$output = $pre_html;
foreach ($comments as $comment) {
$output .= "n<li>".strip_tags($comment->comment_author)
.":" . " <a href="" . get_permalink($comment->ID) .
"#comment-" . $comment->comment_ID . "" title="on " .
$comment->post_title . "">" . strip_tags($comment->com_excerpt)
."</a></li>";
}
$output .= $post_HTML;
echo $output;?>
在wordpress的后台–外观–小工具 里面 你也可以通过拖拽小工具订制边栏模板
一般的主题都有 最近文章 最近评论 的小工具。直接拖入即可实用。