WordPress小工具改造:替换单篇为5篇带图标题的最新文章
Got it, let's tweak your widget to meet your needs! We'll switch it from displaying a single specified post to showing the 5 most recent posts, with only their thumbnails and titles. Here's how we'll adjust the code step by step:
1. Update the Widget Frontend Output
We'll replace the single post fetch with a WP_Query to pull the latest 5 posts, then loop through them to render each post's thumbnail and title. We'll also remove the category info section since you don't need that anymore.
2. Simplify the Admin Form
Since we're no longer targeting a single post, we can remove the post ID input field and keep only the widget title setting.
3. Adjust the Save Logic
We'll strip out the post ID sanitization part since that field is gone now.
Full Modified Code
// 创建小工具前端 function widget($args, $instance) { // Query 5 latest published posts $latest_posts = new WP_Query(array( 'post_type' => 'post', 'posts_per_page' => 5, 'post_status' => 'publish', 'ignore_sticky_posts' => true // 忽略置顶文章,只显示最新的;如果需要包含置顶可删除此行 )); echo $args['before_widget']; if ( !empty($instance['widget_title']) ) { echo $args['before_title'] . $instance['widget_title'] . $args['after_title']; } // Loop through the posts if ($latest_posts->have_posts()) : while ($latest_posts->have_posts()) : $latest_posts->the_post(); ?> <article class="post post-sidebar" itemscope itemtype="https://schema.org/Article"> <?= get_the_post_thumbnail(get_the_ID(), 'thumbnail', ['itemprop' => 'thumbnail']) ?> <h4 itemprop="name"> <a itemprop="url" href="<?= esc_url( get_permalink() ) ?>"> <?= get_the_title() ?> </a> </h4> </article> <?php endwhile; wp_reset_postdata(); // 重置文章数据,避免干扰站点其他内容 endif; echo $args['after_widget']; } function form($instance) { $widget_title = !empty($instance['widget_title']) ? $instance['widget_title'] : ''; ?> <p> <label for="<?= $this->get_field_id('widget_title') ?>"> <?= __('Title of the widget:', 'text-domain') ?> </label> <input class="widefat" type="text" name="<?= $this->get_field_name('widget_title') ?>" value="<?= $widget_title ?>"> </p> <?php } /** * 保存后台表单。 */ function update($new_instance, $old_instance) { $instance = []; $instance['widget_title'] = sanitize_text_field($new_instance['widget_title']); return $instance; }
Key Changes Explained
WP_QuerySetup: We're querying for 5 published posts, with an option to ignore sticky posts (you can removeignore_sticky_postsif you want stickies to appear at the top of the list).- Post Loop: We loop through each returned post, using loop-specific functions like
get_the_post_thumbnail()andget_the_title()directly since we're inside the custom loop. - Reset Post Data:
wp_reset_postdata()ensures WordPress's main post context is restored after our loop, preventing conflicts with other parts of your site. - Cleaned Unused Code: We removed the post ID input from the admin panel and its save logic, plus the category info section that wasn't needed anymore.
内容的提问来源于stack exchange,提问作者gaurav yadav

