自己的随机文章边栏小工具源码

自己主题里边的随机文章Widget的源码,懒人可以直接用,什么都不用改。
 

呢段嘢是自己主题里边的,懒人直接复制到主题 functions.php 里边即刻用得,系小工具里边就会多出个“随机文章”了。
部分代码直接复制WP自带的最近文章,可以自定标题和显示文章数。

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;
			?>
<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('Number of posts to show:'); ?></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");'));

你唔系懒人的话下边讲下你可能要改的地方:
1,里边有三个中文,自己换成取语言的方式,如:_e('random post', 'themes');
2,最后的 add_action widgets_init 可以唔要,将 register_widget("RandomPostWidget"); 加到你主题里边的 widgets_init 度就得了。
3,函数 function widget($args, $instance) 是输出俾人睇的,有需要自己改。
4,自己改成插件都得。

本文发布于 。属于 WordPress点滴 分类,被贴了 标签。

《自己的随机文章边栏小工具源码》有1个评分

★★★★★
★★★★
★★★
★★
0
0
0
0
1

发表回复

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