代码:
$cats = get_terms(array(
'taxonomy' => 'category',
'hide_empty' => false,
));
for ($i=0; $i < count($cats); $i++) {
printf(
'<option value="%s" %s style="margin-bottom:3px;">%s</option>',
$cats[$i]->term_id,
in_array( $cats[$i]->term_id, $categ) ? 'selected="selected"' : '',
$cats[$i]->name
);
}
var_dumping $ categ变量:array(2) { [0]=> string(1) "5" [1]=> string(1) "2" }
当我说var_dumping时,它意味着var_dumping无处不在,在for循环之外,在内部,总是数组。
有人能告诉我地狱里的PHP怎么会给我这个警告吗?
修改
整个form()方法: 并且var_dump如您所见,在带有字段的p标记之前以及在foreach循环之后,都输出数组
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ]; }
else {
$title = __( 'Latest Posts', 'di-news-blog' );
}
if ( isset( $instance ['numPost'] ) ) {
$numPost = $instance[ 'numPost' ]; }
else {
$numPost = __( 3 , 'di-news-blog' );
}
if ( isset( $instance ['categ'] ) ) {
$categ = $instance[ 'categ' ];
}
else {
$categ = __( 'All categories' , 'di-news-blog' );
}
$cats = get_terms(array(
'taxonomy' => 'category',
'hide_empty' => false,
));
// Widget admin form
var_dump($categ); ?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:', 'di-news-blog' ); ?></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 ); ?>" />
<label for="<?php echo $this->get_field_id( 'numPost' ); ?>"><?php _e( 'Number of posts:' , 'di-news-blog' ); ?></label>
<input style="margin-top: 15px" class="tiny-text" id="<?php echo $this->get_field_id( 'numPost' ); ?>" name="<?php echo $this->get_field_name( 'numPost' ); ?>" type="number" step="1" min="1" max="10" value="<?php echo esc_attr( $numPost ); ?>" size="3"><br><br>
<label for="<?php echo $this->get_field_id( 'categ' ); ?>"><?php _e( 'Select categories:' , 'di-news-blog' ); ?></label>
<select multiple style="height:200px" id="<?php echo $this->get_field_id( 'categ' ); ?>" name="<?php echo $this->get_field_name( 'categ' );?>[]">
<option value="" style="margin-bottom:3px;"><?php _e('All categories', 'di-news-blog') ?></option>
<?php
for ($i=0; $i < count($cats); $i++) {
printf(
'<option value="%s" %s style="margin-bottom:3px;">%s</option>',
$cats[$i]->term_id,
in_array( $cats[$i]->term_id, $categ) ? 'selected="selected"' : '',
$cats[$i]->name
);
}
var_dump($categ); ?>
</select>
</p>
<?php
}
答案 0 :(得分:1)
根据您更新的帖子,如果未选择某个类别,则会将$categ
设置为string
值,这就是警告的原因。
$categ = __( 'All categories' , 'di-news-blog' );
在不了解<select>
字段的目的的情况下,很难进一步提出建议。但是一个选项可能是将$categ
设置为未选择类别的空数组。