之前开发的小工具都是用的wp_register_sidebar_widget函数注册的,但是这样的小工具有致命的局限:只能使用一次!为了解决这个问题,经过一下午的查阅资料,不断尝试,用于整理出来了可复用的小工具注册的方法,下面就是详细代码:

class widget_hot extends WP_Widget{
	function __construct(){
			parent::__construct( 'widget_hot', 'QUI 热门文章', array( 'classname' => 'widget_hot' ) );
		}
		function widget( $args, $instance ) {
			extract( $args );
			$title   = apply_filters('widget_name', $instance['title']);
			$limit   = isset($instance['limit']) ? $instance['limit'] : 6;
			echo $before_widget;
			echo $before_title.$title.$after_title; 
			echo '<ul>';
			echo widget_qui_hots( $limit );
			echo '</ul>';
			echo $after_widget;
		}
		function form( $instance ) {
				$defaults = array( 
					'title' => '热门文章', 
					'limit' => 6, 
					'img' => '',
				);
				$instance = wp_parse_args( (array) $instance, $defaults );
		?>
				<p>
					<label>
						标题:
						<input style="width:100%;" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $instance['title']; ?>" />
					</label>
				</p>
				<p>
					<label>
						显示数目:
						<input style="width:100%;" id="<?php echo $this->get_field_id('limit'); ?>" name="<?php echo $this->get_field_name('limit'); ?>" type="number" value="<?php echo $instance['limit']; ?>" size="24" />
					</label>
				</p>
				<p>
					<label>
						<input style="vertical-align:-3px;margin-right:4px;" class="checkbox" type="checkbox" <?php checked( $instance['img'], 'on' ); ?> id="<?php echo $this->get_field_id('img'); ?>" name="<?php echo $this->get_field_name('img'); ?>">显示图片
					</label>
				</p>
			<?php
			}
    	
}
function register_qui_hot(){
        register_widget("widget_hot");
}
add_action("widgets_init", "register_qui_hot");
function widget_qui_hots($limit){
	$args = array(
			'showposts'        => $limit,
			'order'            => 'DESC',
			'orderby' => 'views',
			'ignore_sticky_posts' => 1
	);
	query_posts($args);
	while (have_posts()) : the_post();
	?>
	<li>
		<a  href="<?php the_permalink(); ?>" class="text-h1" title="<?php the_title(); ?>"><?php the_title(); ?></a>
	</li>
	<?php
	endwhile; 
}

以上就是php的代码,扔到functions.php里面就可以在小工具里面找到可复用的小工具了,效果如下:

WordPress 注册可复用的自定义小工具(创建可多次使用的小工具)-QUI-Notes

代码功能还没有完善,先记录下,避免忘记了,年纪大,脑子不好使了!