Wordpress自定义小工具错误


Wordpress Custom Widget error?

我有一个用于注册自定义小部件的wordpress博客的php代码,该小部件从一个类别中获取最新帖子并显示它们。但看起来它在我使用它的一个页面上引发了问题。我找不到任何语法错误。其他人发现这段代码有问题吗?

public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
// before and after widget arguments are defined by themes
echo $args['before_widget'];
if ( ! empty( $title ) )
echo $args['before_title'] . $title . $args['after_title'];
// This is where you run the code and display the output
query_posts( 'category_name=press-release&posts_per_page=5' ); 
while ( have_posts() ) : the_post(); ?>
<div class="about-pg-date"><?php echo get_the_date(); ?></div>
<div class="about-pg-title"><a href="<?php the_permalink(); ?>"><?php echo get_the_title();?></a></div>
<?php
 endwhile; 
echo $args['after_widget'];
}
// Widget Backend 
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'New title', 'thm_widget_domain' );
}
// Widget admin form
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> 
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
</p>
<?php 
}
// Updating widget replacing old instances with new
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
} // Class thm_widget ends here
// Register and load the widget
function thm_load_widget() {
    register_widget( 'thm_widget' );
}
add_action( 'widgets_init', 'thm_load_widget' );

不要使用query_posts来构造自定义查询,这是完全不可预测的,而是使用WP_Query

此外,在使用WP_Querypre_get_posts时,永远不要忘记使用wp_reset_postdata();重置自定义查询。

用这些建议重写您的小部件,如果仍然失败,请发布小部件的完整代码。您当前的代码不完整,因此我无法进行任何测试

您需要使用以下函数:

function register_widget( 'thm_widget' ) thm_widget是函数的类和构造函数。

下面是一个如何在Wordpress中实现的示例。