add_settings_field()
云策文档标注
概述
add_settings_field() 是 WordPress Settings API 的一部分,用于在设置页面的指定部分添加新的设置字段。开发者需通过回调函数输出 HTML 输入标签,并结合 register_setting() 和 get_option() 实现选项的保存与检索。
关键要点
- 函数属于 Settings API,用于定义设置页面中的字段,通过 do_settings_fields() 和 do_settings_sections() 显示。
- 必须使用 register_setting() 注册选项,否则无法自动保存和更新。
- 回调函数需输出 HTML 输入标签,并使用 get_option() 填充旧值,name 属性需与 register_setting() 的 $option_name 匹配。
- 参数包括 $id(字段标识)、$title(标题)、$callback(回调函数)、$page(设置页面)、$section(部分,默认 'default')和 $args(额外参数)。
- $args 可包含 'label_for'(用于包装标签的 for 属性)和 'class'(CSS 类)等选项。
- 支持向默认 WP 设置页面(如 general、reading)添加字段,可添加到现有部分或使用 add_settings_section() 创建新部分。
- 注意:$id 参数在内部用作唯一键,但需在回调中确保 HTML id 属性与其一致,以实现标签关联。
代码示例
add_settings_field( 'myprefix_setting-id',
'This is the setting title',
'myprefix_setting_callback_function',
'general',
'myprefix_settings-section-name',
array( 'label_for' => 'myprefix_setting-id' )
);注意事项
- 在 WordPress 3.0.0 和 3.5.0 中,'misc' 和 'privacy' 页面参数已被弃用,分别重定向到 'general' 和 'reading'。
- 确保 $id、$args['label_for']、register_setting() 的 $option_name 以及回调中的 HTML id 属性一致,以避免保存问题。
- 如果选项存储为数组,HTML 输入标签的 name 属性应为 name="option_name[key]",并在 sanitize_callback 中处理数组组合。
原文内容
Adds a new field to a section of a settings page.
Description
Part of the Settings API. Use this to define a settings field that will show as part of a settings section inside a settings page. The fields are shown using do_settings_fields() in do_settings_sections() .
The $callback argument should be the name of a function that echoes out the HTML input tags for this setting field. Use get_option() to retrieve existing values to show.
Parameters
$idstringrequired-
Slug-name to identify the field. Used in the
'id'attribute of tags. $titlestringrequired-
Formatted title of the field. Shown as the label for the field during output.
$callbackcallablerequired-
Function that fills the field with the desired form inputs. The function should echo its output.
$pagestringrequired-
The slug-name of the settings page on which to show the section (general, reading, writing, …).
$sectionstringoptional-
The slug-name of the section of the settings page in which to show the box. Default
'default'. $argsarrayoptional-
Extra arguments that get passed to the callback function.
label_forstringWhen supplied, the setting title will be wrapped in a<label>element, itsforattribute populated with this value.classstringCSS Class to be added to the<tr>element when the field is output.
Default:
array()
Source
function add_settings_field( $id, $title, $callback, $page, $section = 'default', $args = array() ) {
global $wp_settings_fields;
if ( 'misc' === $page ) {
_deprecated_argument(
__FUNCTION__,
'3.0.0',
sprintf(
/* translators: %s: misc */
__( 'The "%s" options group has been removed. Use another settings group.' ),
'misc'
)
);
$page = 'general';
}
if ( 'privacy' === $page ) {
_deprecated_argument(
__FUNCTION__,
'3.5.0',
sprintf(
/* translators: %s: privacy */
__( 'The "%s" options group has been removed. Use another settings group.' ),
'privacy'
)
);
$page = 'reading';
}
$wp_settings_fields[ $page ][ $section ][ $id ] = array(
'id' => $id,
'title' => $title,
'callback' => $callback,
'args' => $args,
);
}
Skip to note 7 content
Codex
With Label
Adds a setting with id
myprefix_setting-idto the General Settings page.myprefixshould be a unique string for your plugin or theme. Sets a label so that the setting title can be clicked on to focus on the field.add_settings_field( 'myprefix_setting-id', 'This is the setting title', 'myprefix_setting_callback_function', 'general', 'myprefix_settings-section-name', array( 'label_for' => 'myprefix_setting-id' ) );Skip to note 8 content
tradesouthwest
A checkbox settings field can be checked on the front end by simply looking for isset. No need to add additional checks like 1, 0, true, false…. if a checkbox is not set then it returns false.
/* **************** CHECKBOXES **************** */ // settings checkbox add_settings_field( 'wpdevref_removestyles_field', esc_attr__('Remove Plugin Styles', 'wpdevref'), 'wpdevref_removestyles_field_cb', 'wpdevref_options', 'wpdevref_options_section', array( 'type' => 'checkbox', 'option_group' => 'wpdevref_options', 'name' => 'wpdevref_removestyles_field', 'label_for' => 'wpdevref_removestyles_field', 'value' => (empty(get_option('wpdevref_options')['wpdevref_removestyles_field'])) ? 0 : get_option('unitizr_options')['wpdevref_removestyles_field'], 'description' => __( 'Check to remove preset plugin overrides.', 'wpdevref' ), 'checked' => (!isset(get_option('wpdevref_options')['wpdevref_removestyles_field'])) ? 0 : get_option('wpdevref_options')['wpdevref_removestyles_field'], // Used 0 in this case but will still return Boolean not[see notes below] 'tip' => esc_attr__( 'Use if plugin fields drastically changed when installing this plugin.', 'wpdevref' ) ) );Then the callback would be added as such:
/** * switch for 'remove styles' field * @since 2.0.1 * @input type checkbox */ function wpdevref_removestyles_field_cb($args) { $checked = ''; $options = get_option($args['option_group']); $value = ( !isset( $options[$args['name']] ) ) ? null : $options[$args['name']]; if($value) { $checked = ' checked="checked" '; } // Could use ob_start. $html = ''; $html .= '<input id="' . esc_attr( $args['name'] ) . '" name="' . esc_attr( $args['option_group'] . '['.$args['name'].']') .'" type="checkbox" ' . $checked . '/>'; $html .= '<span class="wndspan">' . esc_html( $args['description'] ) .'</span>'; $html .= '<b class="wntip" data-title="'. esc_attr( $args['tip'] ) .'"> ? </b>'; echo $html; }And checking to render action on the front side would use:
// Options getter could be a function with arguments. $options = get_option('wpdevref_options'); $value = ( !isset($options['wpdevref_removestyles_field'] ) ) ? '' : $options['wpdevref_removestyles_field']; if ( !$value ) { // Do some magic }Optionally you can add a ‘false’ into any conditional (empty, null, ”, 0).
Skip to note 9 content
princepink
I suspect Used in the ‘id’ attribute of tags might be rewritten to Used in the ‘name’ attribute of tags.
I think the $id param is used for identifying the field to be recognised by WP and to show the field or get that’s value. Whether to be used as actual tag’s attribute id‘s value or not depends on the circumstances (in $callback). Normally the name attribute might be taken for this aim.
I just had been confused this param means to generate the attribute for some form element, but it seems not. When put ‘label_for’ in the $args that will be passed to the $callback, this generates label tag with attribute for automatically. So this value should be same as an actual id‘s value in the $callback which you write.
Skip to note 10 content
tehlivi
add_action('admin_init', 'your_function'); function your_function(){ add_settings_field( 'myprefix_setting-id', 'This is the setting title', 'myprefix_setting_callback_function', 'general', 'default', array( 'label_for' => 'myprefix_setting-id' ) ); } function myprefix_setting_callback_function($args){ echo 'Content here'; }Skip to note 11 content
Bence Szalai
The
$idargument description says “Used in the ‘id’ attribute of tags”, however this means you have to ensure this$idis used as the HTMLidtag of yourinputelement related to the field. WP only use this$idto have an unique key for your field in it’s internal settings_field list ($wp_settings_fields).As WP does not control the way the input element is added to your Admin HTML, you have to ensure you output the input element with an
idthat matches the$idtag. This can be done by configuring the$callbackto a function, that will produce the correctinputelement with the correctidtag.The ‘label_for’ element in the $args array should also match the very same
idin order for the browser to understand whichlabelbelongs to whichinputfield.It worth noting also, that the
idtag of theinputelement should also match the $option_name (2nd) parameter you are using in yourregister_setting()call, otherwise the Settings API will fail to match the value sent by the browser in$_POSTto your setting, and your setting will never be saved.So long story short, we have a bunch of different names and arguments, but basically
$idand$args['label_for']ofadd_settings_field()call and the$option_nameofregister_setting()call PLUS theidyou use in your input field callback, should all be the same, uniqueid. Also the sameidshould be used as the$optionparameter in theget_option($option)calls to get the value of the setting.register_setting( 'mygroup', 'mynewcheckboxID' ); add_settings_field( 'mynewcheckboxID', 'My New Checkbox', 'callback_input_myid', 'myAdminPage', 'myAdminSection', [ 'label_for' => 'mynewcheckboxID' ] ); function callback_input_myid() { echo "<input type='checkbox' id='mynewcheckboxID' value='1'" if ( get_option('mynewcheckboxID') == '1' ) { echo ' checked'; } echo '/>'; }name="<em>option_name</em>[<em>key</em>]". The option_name is the value passed toregister_setting()(the 2nd parameter). The key sets the key of the key=>value pair in the resulting associative array that is passed to yoursanitize_callbackhandler. Even thoughregister_setting()‘s optional $args parameter can state that your option type is an array, there is no automatic combining or separating of individual key=>value pairs you might be storing within the array. That needs to be done by you in yoursanitize_callbackhandler, after youget_option(), and in theadd_settings_field()callbacks.Skip to note 12 content
tehlivi
Object Oriented:
class ClassName { public function __construct() { add_action( 'admin_init', array( $this, 'your_function' ) ); } function your_function() { add_settings_field( 'myprefix_setting-id', 'This is the setting title', array( $this, 'myprefix_setting_callback_function' ), 'general', 'default', array( 'label_for' => 'myprefix_setting-id' ), ); } function myprefix_setting_callback_function( $args ) { echo 'Content here'; } } $ClassName = new ClassName();class ClassName { public function __construct() { add_action( 'admin_init', array( $this, 'your_function' ) ); } function your_function() { add_settings_field( 'myprefix_setting-id', 'This is the setting title', array( $this, 'myprefix_setting_callback_function' ), 'general', 'default', array( 'label_for' => 'myprefix_setting-id' ) ); } function myprefix_setting_callback_function( $args ) { echo 'Content here'; } } $ClassName = new ClassName();