add_settings_field()
接受六个参数,最后一个是参数数组:
add_settings_field($id, $title, $callback, $page, $section, $args);
您可以在此处添加自定义值,以便重用一个回调。
一个简单的例子:
add_settings_field(
\'foo\',
\'Foo\',
\'wpse_settingsfield_callback\',
\'my_page\',
\'my_section\',
array ( \'context\' => \'foo\' ) // custom arguments
);
add_settings_field(
\'bar\',
\'Bar\',
\'wpse_settingsfield_callback\',
\'my_page\',
\'my_section\',
array ( \'context\' => \'bar\' ) // custom arguments
);
function wpse_settingsfield_callback( $args )
{
if ( \'foo\' === $args[ \'context\' ] )
print \'Hello Foo!\';
elseif ( \'bar\' === $args[ \'context\' ] )
print \'Hello Bar!\';
else
print \'Unknown context!\';
}
另一个选项是用于场渲染的单独类。让我们学习一门非常简单且不完整的课程:
class Checkbox_Settingsfield_View {
protected $attributes, $label;
public function set_attributes( Array $attributes )
{
$this->attributes = $attributes;
}
public function render()
{
printf(
\'<label for="%1$s"><input type="checkbox"%2$s /></label>\',
$this->attributes[ \'id\' ],
$this->array_to_attrs( $this->attributes )
);
}
protected function array_to_attrs( array $attrs, $xml = TRUE )
{
$str = \'\';
foreach ( $attrs as $key => $value ) {
if ( TRUE === $value )
( $xml and $value = "=\'$key\'" ) or $value = \'\';
$str .= " $key=\'" . esc_attr( $value) . "\'";
}
return $str;
}
}
现在设置对象…
$foo_view = new Checkbox_Settingsfield_View;
$foo_view->set_attributes(
array (
\'name\' => \'foo\',
\'style\' => \'border:10px solid red\'
)
);
$bar_view = new Checkbox_Settingsfield_View;
$bar_view->set_attributes(
array (
\'name\' => \'bar\',
\'style\' => \'border:5px solid blue\'
)
);
…并通过方法
render()
作为回调参数:
add_settings_field(
\'foo\',
\'Foo\',
array ( $foo_view, \'render\' ),
\'my_page\',
\'my_section\'
);
add_settings_field(
\'bar\',
\'Bar\',
array ( $bar_view, \'render\' ),
\'my_page\',
\'my_section\'
);