随机文章,对于SEO而言是非常有用的,就算你的网站长时间不更新,快照也会经常光顾你的网站从而更新你的快照。所以调用随机文章等等是非常有必要的,我们可以通过插件非常简单的来实现,也可以调用以下代码作为参考和修改,在wordpress后台添加一个随机文章的小工具,这样会提高你的网站速度,具体方法如下:
修改模板functions.php 文件
注意: PHP 5.2+才支持,看看你的Php版本是否支持。
如果你的 WordPress 中插件已经十几个了,不希望增加太多的插件造成网页负担,所以就在主题的 functions.php 文件中增加了一个函数类来完成这个任务。
将下面的代码直接,或定制化修改后放入主题的 functions.php 文件中即可。没有functions.php文件的话在主题更目录下创建一个。这样在WordPress 后台中的“小工具”里就会增加一个“随机文章”的可用小工具,将其添加到边栏中作为微件显示出来。
效果如下:
//随机文章小工具
class RandomPostWidget extends WP_Widget
{
function RandomPostWidget()
{
parent::WP_Widget('bd_random_post_widget','随机文章',array('description' => '我的随机文章小工具') );
}
function widget($args,$instance)
{
extract( $args );
$title = apply_filters('widget_title',empty($instance['title']) ? '随机文章' :
$instance['title'],$instance,$this->id_base);
if ( empty( $instance['number'] ) || ! $number = absint( $instance['number'] ) )
{
$number = 10;
}
$r = new WP_Query(array('posts_per_page' => $number,'no_found_rows' => true,
'post_status' => 'publish','ignore_sticky_posts' => true,'orderby' =>'rand'));
if ($r->have_posts())
{
echo "n";
echo $before_widget;
if ( $title ) echo $before_title . $title . $after_title;
?>
echo $after_widget;
wp_reset_postdata();
}
}
function update($new_instance,$old_instance)
{
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['number'] = (int) $new_instance['number'];
return $instance;
}
function form($instance)
{
$title = isset($instance['title']) ? esc_attr($instance['title']) : '';
$number = isset($instance['number']) ? absint($instance['number']) : 10;?>
show:'); ?>
}
}
add_action('widgets_init',create_function('','return register_widget("RandomPostWidget");'));
?>
带有缩略图的随机文
如果你想自己实现带有缩略图的随机文章功能,建议你阅读wordpressWordPress 开发带缩略图随机文章小工具