更新日期:2021-10-12

幾乎所有網站都會使用「近期文章」這個小工具,但是它可供設定的項目非常稀少,有時候想要變化一下就必須找其他小工具來取代。不過我比較喜歡利用現有的去擴充它,底下我新增了兩個小功能。

這裡我新增了兩項小功能,第一項是「清單不含當前文章」,這項是網友提出的想法。當停留在某篇文章時,此文章又剛好顯示在近期文章清單內,這樣子就有點浪費了一個顯示位置。
第二項是「只顯示當前文章分類的相關文章」,也是當停留在某篇文章時,近期文章最好是顯示相關文章才比較會吸引網友繼續點擊,因此只顯示和該文章有相同分類的最適合。

在設定表單中新增新的欄位

在近期文章小工具的設定項目下,透過 in_widget_form 新增欄位

add_action('in_widget_form', function($widget, $return, $instance) {

	if ($widget->id_base != 'recent-posts') {
		return;
	}

?>
	<p>
		<input type="checkbox" class="checkbox" name="<?php echo $widget->get_field_name('exclude-post-id'); ?>" id="<?php echo $widget->get_field_name('exclude-post-id'); ?>" <?php checked(isset($instance['exclude-post-id']) ? $instance['exclude-post-id'] : 0); ?> />
		<label for="<?php echo $widget->get_field_name('exclude-post-id'); ?>">清單不含當前文章</label>
	</p>

	<p>
		<input type="checkbox" class="checkbox" name="<?php echo $widget->get_field_name('post-filter-cates'); ?>" id="<?php echo $widget->get_field_name('post-filter-cates'); ?>" <?php checked(isset($instance['post-filter-cates']) ? $instance['post-filter-cates'] : 0); ?> />
		<label for="<?php echo $widget->get_field_name('post-filter-cates'); ?>">只顯示當前文章分類的相關文章</label>
	</p>

	<?php
}, 10, 3);

儲存新欄位的設定值

要將新增接收變數的欄位儲存它

add_filter('widget_update_callback', function($instance, $new_instance, $old_instance) {
	$instance['exclude-post-id']	= isset($new_instance['exclude-post-id']);
	$instance['post-filter-cates']	= isset($new_instance['post-filter-cates']);
	return $instance;
}, 10, 3);

新增文章過濾條件

我們的篩選方式,要加入 $args 中

add_filter('widget_posts_args', function ($args, $instance) {
	if( is_single() && is_singular() ){
		$post_id = get_the_ID();
		if( !empty($instance['exclude-post-id']) ){
			if( !empty($post_id) ) $args['post__not_in'] = array($post_id);
		}
		if( !empty($instance['post-filter-cates']) ){
			$args['category__in'] = wp_get_post_categories( $post_id );
		}
	}
	return $args;
}, 10, 2);

總結

以上三段語法,你可以儲存在佈景的 functions.php 內,或是利用 Code Snippets 這類外掛直接寫進去也是很方便。日後若有想到其他功能,我會繼續擴充它。