/ 博客 / 741浏览

WordPress添加随机文章小工具

为排版需要,想把随机文章(random posts)小工具加到页脚,由于某些主题不自带,必须自己制作。本着尽可能不用插件的原则到网上搜了一下,有简单的办法,有复杂的办法,此文《为wordpress主题添加随机文章小工具》是比较方便快捷的,经实际体验,去除掉其中一些莫名其妙的格式和代码后把通用代码公布于众。

找到主题的functions.php,在?>之前添加如下代码:

//随机文章
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 $before_widget;
		if ( $title ) echo $before_title . $title . $after_title;
?>
	<ul>
	<?php while ($r->have_posts()) : $r->the_post(); ?>
		<li>
			<a href="<?php the_permalink() ?>" title="<?php echo esc_attr(get_the_title() ? get_the_title() : get_the_ID()); ?>"><?php if ( get_the_title() ) the_title(); else the_ID(); ?></a>
		</li>
	<?php endwhile; ?>
	</ul>
	<?php
	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;?>
	<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label>
	<input id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" /></p>

	<p><label for="<?php echo $this->get_field_id('number'); ?>"><?php _e('文章显示数量:'); ?></label>
	<input id="<?php echo $this->get_field_id('number'); ?>" name="<?php echo $this->get_field_name('number'); ?>" type="text" value="<?php echo $number; ?>" size="3" /></p>
<?php
}
}
add_action('widgets_init', create_function('', 'return register_widget("RandomPostWidget");'));

2

  1. Betty

    以前挺喜欢这功能,后来又不喜欢了

    Safari 7 · Mac OS X 10.9
    1. S

      @Betty嗯,只是放出一个方法,方便后来人……

      Opera 23 · Windows 7

回复 S 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注