WordPress更新后自定义Featured Posts小部件加载页面而非文章如何修正?
问题根因
WordPress版本更新后,你站点内的主题或其他插件的pre_get_posts钩子修改了自定义查询的逻辑,导致原本指定查询文章的配置被篡改,同时原代码中查询数据重置的用法不符合规范,共同造成了加载页面而非文章的问题。
修复方案
对小部件代码做两处核心修改即可:
- 在
WP_Query的查询参数中新增suppress_filters => true,屏蔽外部钩子对当前自定义查询的影响 - 将查询结束后的
wp_reset_query()替换为wp_reset_postdata(),这是自定义二级查询重置全局变量的规范用法
修改后的完整代码如下:
class Event_Featured_Posts_Widget extends WP_Widget { // setup the widget name, description, etc... public function __construct() { $widget_ops = array( 'classname' => 'widget-featured-posts', 'description' => 'Display Featured Posts Widget', ); parent::__construct( 'event_featured_posts', 'Featured Posts', $widget_ops ); } // back-end display of widget public function form( $instance ) { echo '<p><strong>No options for this Widget!</strong></p>'; } // front-end display of widget public function widget( $args, $instance ) { $postfeat = array( 'post_type' => 'post', //write slug of post type 'post_status' => 'publish', 'category_name' => 'featured', 'posts_per_page' => 3, 'suppress_filters' => true, // 新增:屏蔽外部查询钩子干扰 ); $featPosts = new WP_Query( $postfeat ); echo $args['before_widget']; ?> <div class="text-center"> <div class="row"> <h2 class="event-widget-title">Featured Posts</h2> </div> <div class="row text-center" id="featured"> <?php if ( $featPosts->have_posts() ) : ?> <?php while ( $featPosts->have_posts() ) : $featPosts->the_post(); ?> <div class="featured-posts-box col-md-4 col-sm-12 col-xs-12"> <?php if( event_get_attachment() ): ?> <a class="standard-featured-link" href="<?php the_permalink(); ?>"> <div class="standard-featured background-image" style="background-image: url(<?php echo event_get_attachment(); ?>);"> <img class="image-invisible" src="<?php echo event_get_attachment(); ?>"> </div> </a> <?php endif; ?> <div class="featured-posts-text"> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <!-- <p><?php the_excerpt(); ?></p> --> <div class="featured-entry-meta text-center"> <?php echo event_posted_meta(); ?> </div> <!-- <p id="featured_excerpt"><a href="<?php the_permalink(); ?>">Read More >></a></p> --> </div> </div> <?php endwhile; ?> <?php endif; ?> <?php wp_reset_postdata(); // 替换原wp_reset_query(),规范重置逻辑 ?> </div><!--featured--> </div> <?php echo $args['after_widget']; } } add_action( 'widgets_init', function() { register_widget( 'Event_Featured_Posts_Widget' ); } );
如果修改后仍有异常,可将category_name => 'featured'替换为cat => 分类ID(将分类ID替换为你后台「Featured」分类对应的数字ID),避免分类别名变动导致的查询失效。
内容的提问来源于stack exchange,提问作者bennie
相关产品推荐
相关产品推荐

