你好WordPress答案!
我的小部件有问题update
函数正确保存值,但首先让我解释一下情况。
我正在编写一个简单的新闻报价器小部件插件,它通过小部件设置表单中的复选框过滤按帖子类型显示的帖子。要生成复选框,我使用foreach
循环查看可用的帖子类型。
但是,小部件更新功能没有保存post类型值。我通过做一个print_r
在表单函数中(值存在)和小部件函数中(值不存在)。
这是我的代码:
class ami_newsticker_widget extends WP_Widget {
// process the widget
function ami_newsticker_widget () {
$widget_ops = array(
\'classname\' => \'ticketcontainer\',
\'description\' => \'Display a scrolling newsticker\'
);
$this->WP_Widget( \'ami_newsticker_widget\', \'AMI News Ticker Widget\', $widget_ops );
}
// build the widget settings form
function form( $instance ) {
$defaults = array( \'num_posts\' => 5 );
$instance = wp_parse_args( (array) $instance, $defaults );
$num_posts = $instance[\'num_posts\'];
foreach ( get_post_types() as $post_type ) {
$instance[\'post_types\'] .= $post_type . \',\';
}
$post_types = $instance[\'post_types\'];
//echo \'<pre>\';
//print_r($instance);
//echo \'</pre>\';
?>
<p>Number of posts to show: <input class="widefat" name="<?php echo $this->get_field_name( \'num_posts\' ); ?>" type="number" value="<?php echo esc_attr( $num_posts ); ?>" /></p>
<p>Filter by Post Type: <ul>
<?php foreach ( get_post_types() as $post_type ) { ?>
<li><input name="<?php echo $this->get_field_name( $post_type ); ?>" type="checkbox" <?php checked( $this->get_field_name( $post_type ) ); ?> /><label for="<?php echo $this->get_field_name( $post_type ); ?>" /><?php echo $post_type; ?></label></li>
<?php
} ?>
</ul></p>
<?php
echo \'<pre>\';
print_r($instance);
echo \'</pre>\';
}
// save the widget settings
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance[\'num_posts\'] = strip_tags( $new_instance[\'num_posts\'] );
$instance[\'post_types\'] = strip_tags( $new_instance[\'post_types\'] );
return $instance;
}
// display the widget
function widget( $args, $instance ) {
global $wpdb;
extract( $args );
echo \'<pre>\';
print_r($instance);
echo \'</pre>\';
// load the widget settings
//foreach ( $instance[\'post_types\'] as $post_type ) {
//if ( $post_type == \'on\' ) {
//$checked .= $instance[\'post_types\'][$post_type] . \' ,\';
//}
//}
//echo $checked;
// get and clean the db data
$num_posts = intval( absint( $instance[\'num_posts\'] ) );
$sql = "SELECT post_title, guid
FROM {$wpdb->posts}
WHERE post_status = \'publish\'
ORDER BY post_date DESC
LIMIT {$num_posts}";
$results = $wpdb->get_results( $sql );
// print the widget
echo $before_widget;
echo \'<ul id="webticker">\';
foreach ($results as $result) {
echo \'<li><a href="\' . $result->guid . \'">\' . $result->post_title . \'</a></li>\';
}
echo \'</ul>\';
echo $after_widget;
}
}似乎有什么明显的东西我遗漏了,但我一直在用头撞墙!
任何帮助都将不胜感激。提前感谢!