如何設計顯示最新文章的小工具

由於內建的最近文章的小工具實在太不好用了,所以小編就自己製作了一個近期文章的小工具。

原始提供的工具

改善後的工具

class Recent_Posts_Widget extends WP_Widget {

// 設定小工具
function __construct() {
parent::__construct(
'recent_posts_widget', // Base ID
__('Recent Posts Widget', 'text_domain'), // Name
array('description' => __('A Widget to display recent posts', 'text_domain'),) // Args
);
}

// 前端顯示
public function widget($args, $instance) {
echo $args['before_widget'];

if (!empty($instance['title'])) {
echo $args['before_title'] . apply_filters('widget_title', $instance['title']) . $args['after_title'];
}

// 在这里嵌入 CSS 样式
echo '';

// 獲取最近的文章
$recent_posts = wp_get_recent_posts(array(
'numberposts' => 5, // 你可以在這裡調整要顯示的文章數量
'post_status' => 'publish'
));

if (!empty($recent_posts)) {
echo '';
$counter = 1;
foreach ($recent_posts as $post) {
// 獲取文章的閱讀次數
$post_views = pvc_get_post_views($post['ID']); // 使用 Post Views Counter 插件的函數

echo ''
. $counter . '. '
. $post['post_title'] . ' ('
. $post_views
. ' 次閱覽)';
$counter++;
}
echo '';
} else {
echo '' . __('No recent posts available.', 'text_domain') . '';
}

echo $args['after_widget'];
}

// 後端小工具設定
public function form($instance) {
$title = !empty($instance['title']) ? $instance['title'] : __('Recent Posts', 'text_domain');
?>

<label for="">
<input class="widefat" id="" name="" type="text" value="">

<?php
}

// 儲存小工具設定
public function update($new_instance, $old_instance) {
$instance = array();
$instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';

return $instance;
}
}

// 註冊小工具
function register_recent_posts_widget() {
register_widget('Recent_Posts_Widget');
}

add_action('widgets_init', 'register_recent_posts_widget');