我开发了一个小部件来显示最新消息。小部件功能正常工作,但问题是小部件标题未保存在后端。正确的方法是什么?
class infotravel_news_list_widget extends WP_Widget {
public function __construct() {
parent::__construct( false, $name = __( \'Latest News\', \'infotravel\' ) );
}
public function form( $instance ) {
$defaults = array(
\'title\' => \'\',
);
extract( wp_parse_args( array( $instance, $defaults ) ) );
// Widget title ?>
<p>
<label for="<?php echo esc_attr( $this->get_field_id( \'title\' ) ); ?>"><?php _e( \'Title\', \'infotravel\' ); ?></label>
<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( \'title\' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( \'title\' ) ); ?>" type="text" value="<?php echo esc_attr( $defaults[\'title\'] ); ?>" />
</p>
<?php
}
public function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance[\'title\'] = isset( $new_instance[\'title\'] ) ? wp_strip_all_tags( $new_instance[\'title\'] ) : \'\';
return $instance;
}
public function widget( $args, $instance ) {
$news_args = array(
\'post_type\' => \'infotravel_news\',
\'posts_per_page\' => 5,
\'post_status\' => \'publish\',
\'orderby\' => \'post_date\',
\'order\' => \'desc\'
);
$query = new WP_Query( $news_args );
if( $query -> have_posts() ) :
while( $query -> have_posts() ) : $query -> the_post(); ?>
<h3><?php the_title(); ?></h3>
<?php
endwhile;
endif;
?>
<?php }
}
add_action( \'widgets_init\', function(){
register_widget( \'infotravel_news_list_widget\' );
} );