這是非常重要的作法
因為wordpress裡面的小工具,並沒有這項功能。
大部分要讓小工具有「分類的最新文章」
都是用外掛實現。
外掛很麻煩,我們能用代碼就用代碼。作法很簡單。
打開你主題的functions.php
加入以下代碼
[cc lang="php"] //分類的最新文章小工具 function register_catlist_widget(){ register_widget('catlist_widget'); } add_action('widgets_init','register_catlist_widget'); class Catlist_Widget extends wp_Widget{ /** * 定義wp_Widget類型,設置小工具名和描述 * Sets up the widget name and description */ public function __construct(){ $widget_ops = array('classname' => 'catlist_widget', 'description' => '指定分類目錄與顯示數目' ); // parent::__construct()調用定義函數 parent::__construct( 'category-post-list', // Base ID __('指定分類目錄文章列表','text_domain'), // Name $widget_ops // Args ); // add_action( $tag, $function_to_add); add_action( 'save_post', array($this, 'flush_widget_cache') ); add_action( 'deleted_post', array($this, 'flush_widget_cache') ); add_action( 'switch_theme', array($this, 'flush_widget_cache') ); } /** * Outputs the content of the widget * @param [array] $args [description] * @param [array] $instance [description] * @return [type] [description] */ public function widget($args,$instance){ $cache = array(); if ( ! $this->is_preview() ) { $cache = wp_cache_get( 'catlist_posts', 'widget' ); } if ( ! is_array( $cache ) ) { $cache = array(); } if ( ! isset( $args['widget_id'] ) ) { $args['widget_id'] = $this->id; } if ( isset( $cache[ $args['widget_id'] ] ) ) { echo $cache[ $args['widget_id'] ]; return; } ob_start(); $title = ( ! empty( $instance['title'] ) ) ? $instance['title'] : '分類文章列表'; $title = apply_filters( 'widget_title', $title, $instance, $this->id_base ); $number = ( ! empty( $instance['num'] ) ) ? absint( $instance['num'] ) : 10; if ( ! $number ) $number = 10; $catid = ( ! empty( $instance['cat'] ) ) ? absint( $instance['cat'] ) : 1; if ( ! $catid ) $catid = 1; global $post; $r = new wp_Query( apply_filters('widget_posts_args', array( 'posts_per_page' => $number, 'cat' => $catid, 'post_status' => 'publish', 'no_found_rows' => true ))); if ($r->have_posts()) : ?>
- have_posts() ) : $r->the_post(); ?>