在这一部分,我将向你展示如何为你的WordPress小工具创建表单,确保WordPress能够在上面进行任何的设置更新。
这意味着你要为Tutsplus_List_Pages_Widget类编写两个函数:form函数和update函数。
创建表单
function form( $instance ) {
$defaults = array(
'depth' => '-1'
);
$depth = $instance[ 'depth' ];
// markup for form ?>
<p>
<label for="<?php echo $this->get_field_id( 'depth' ); ?>">Depth of list:</label>
<input class="widefat" type="text" id="<?php echo $this->get_field_id( 'depth' ); ?>" name="<?php echo $this->get_field_name( 'depth' ); ?>" value="<?php echo esc_attr( $depth ); ?>">
</p>
<?php
}
保存你的插件。你会发现WordPress小工具出现了一个表单
但是,如果你尝试在其中输入一些内容,它不会被保存下来。因此你需要进一步完善让这个表单能保存你所输入的内容。
允许表单更新
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance[ 'depth' ] = strip_tags( $new_instance[ 'depth' ] );
return $instance;
}
说明:
上述代码用新值($new_instance)代替了depth字段的旧值($old_instance),并采用strip_tags进行。现在你可以在其中进行任意的输入并保存了。
小结
现在你终于为你的WordPress小工具创建了一个工作表单,可以说一切都准备就绪了,那么下一步就是在网站上显示你的WordPress小工具啦!
strip_tags() 的实际使
<?php
echo strip_tags("Hello <b>world!</b>");
?>
运行后会输出Hello world!
strip_tags() 函数剥去字符串中的 HTML、XML 以及 PHP 的标签,并且始终会剥离HTML中的注释,函数将返回剥离后的字符串。
语法:
strip_tags(string,allow)
string为必需,需要检查的字符串
allow为可选,可以加入允许的标签
在编程平台搭建中,发现由于使用了HTML代码生成器,数据库中包括样例输入和样例输出,均包含了HTML标签,为后期修改样例造成了不变,故使用strip_tags() 函数将生成器所生成的HTML标签过滤掉,提供更完善的用户体验。