指定分類目錄下的最新文章列表小工具widget

Posted by Y Cheung on Wed, Dec 3, 2014

根據需求模仿著wordpress官方原生小工具(widget) 寫了一個能夠列出指定分類目錄下最新文章列表的小工具。代碼如下(先貼出來,以後有空再做解釋說明):

  1<?php
  2	function register_catlist_widget(){
  3	register_widget('catlist_widget');
  4	}
  5	add_action('widgets_init','register_catlist_widget');
  6
  7	class Catlist_Widget extends WP_Widget{
  8	/**
  9	 * 定义WP_Widget扩展类,设置小工具名和描述
 10     * Sets up the widget name and description
 11	 */
 12	public function __construct(){
 13		$widget_ops = array('classname' => 'catlist_widget', 'description' => '指定分類目錄與顯示數目' );
 14        // parent::__construct()调用父类定义函数
 15		parent::__construct(
 16			'category-post-list', // Base ID
 17			__('指定分類目錄文章列表','text_domain'), // Name
 18            $widget_ops // Args
 19            );
 20
 21		// add_action( $tag, $function_to_add);
 22        add_action( 'save_post', array($this, 'flush_widget_cache') );
 23		add_action( 'deleted_post', array($this, 'flush_widget_cache') );
 24		add_action( 'switch_theme', array($this, 'flush_widget_cache') );
 25
 26	}
 27
 28	/**
 29	 * Outputs the content of the widget
 30	 * @param  [array] $args     [description]
 31	 * @param  [array] $instance [description]
 32	 * @return [type]           [description]
 33	 */
 34	public function widget($args,$instance){
 35		$cache = array();
 36		if ( ! $this->is_preview() ) {
 37			$cache = wp_cache_get( 'catlist_posts', 'widget' );
 38		}
 39
 40		if ( ! is_array( $cache ) ) {
 41			$cache = array();
 42		}
 43
 44		if ( ! isset( $args['widget_id'] ) ) {
 45			$args['widget_id'] = $this->id;
 46		}
 47
 48		if ( isset( $cache[ $args['widget_id'] ] ) ) {
 49			echo $cache[ $args['widget_id'] ];
 50			return;
 51		}
 52
 53		ob_start();
 54
 55
 56		$title = ( ! empty( $instance['title'] ) ) ? $instance['title'] : '分類文章列表';
 57		$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
 58
 59		$number = ( ! empty( $instance['num'] ) ) ? absint( $instance['num'] ) : 10;
 60		if ( ! $number )
 61			$number = 10;
 62		$catid = ( ! empty( $instance['cat'] ) ) ? absint( $instance['cat'] ) : 1;
 63		if ( ! $catid )
 64			$catid = 1;
 65
 66		global $post;
 67		$r = new WP_Query( apply_filters('widget_posts_args', array(
 68			'posts_per_page'      => $number,
 69			'cat' 				  => $catid,
 70			'post_status'         => 'publish',
 71			'no_found_rows'       => true
 72			)));
 73		if ($r->have_posts()) :
 74	?>
 75		<?php echo $args['before_widget']; ?>
 76		<?php if ( $title ) {
 77			echo $args['before_title'] . $title . $args['after_title'];
 78		} ?>
 79				<ul>
 80		<?php while ( $r->have_posts() ) : $r->the_post(); ?>
 81			<li>
 82				<a href="<?php the_permalink(); ?>"><?php get_the_title() ? the_title() : the_ID(); ?></a>
 83			</li>
 84		<?php endwhile; ?>
 85		<li><a href="<?php echo get_category_link($catid); ?>">more...</a></li>
 86		</ul>
 87		<?php echo $args['after_widget']; ?>
 88	<?php
 89		// Reset the global $the_post as this query will have stomped on it
 90		wp_reset_postdata();
 91
 92		endif;
 93
 94		if ( ! $this->is_preview() ) {
 95			$cache[ $args['widget_id'] ] = ob_get_flush();
 96			wp_cache_set( 'catlist_posts', $cache, 'widget' );
 97		} else {
 98			ob_end_flush();
 99		}
100	}
101	public function update( $new_instance, $old_instance ) {
102		$instance = $old_instance;
103		$instance['title'] = strip_tags($new_instance['title']);
104		$instance['num'] = (int) $new_instance['number'];
105		$instance['cat'] = (int) $new_instance['cat'];
106		$this->flush_widget_cache();
107
108		$alloptions = wp_cache_get( 'alloptions', 'options' );
109		if ( isset($alloptions['catlist_widget']) )
110			delete_option('catlist_widget');
111
112		return $instance;
113	}
114
115	public function flush_widget_cache() {
116		wp_cache_delete('catlist_posts', 'widget');
117	}
118	
119
120	/**
121	 * Back-end widget form.
122	 * @see  WP_Widget::form()
123	 * @param  [array] $instance [description]
124	 * @return [type]           [description]
125	 */
126	public function form($instance){
127		$title     = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : '';
128		$number    = isset( $instance['num'] ) ? absint( $instance['num'] ) : 10;
129		$catid 	   = isset( $instance['cat']) ? absint( $instance['cat'] ):'';
130		 ?>
131		 <p><label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
132		<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo $title; ?>" /></p>
133
134		<p><label for="<?php echo $this->get_field_id( 'number' ); ?>"><?php _e( 'Number of posts to show:' ); ?></label>
135		<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>
136		
137		<p><label><?php wp_dropdown_categories(array('name'=>$this->get_field_name('cat'),'selected'=>$instance['cat']));?></label></p>
138		<?php
139	}
140	}

在小工具(widget)界面添加後的設置效果如下圖示:

参考官方文档:Widgets API