函数文档

settings_fields()

💡 云策文档标注

概述

settings_fields() 函数用于在 WordPress 设置页面输出必要的隐藏字段,包括 nonce、action 和 option_page,以确保表单提交的安全性和正确性。

关键要点

  • 函数输出 nonce、action 和 option_page 字段,用于设置页面的表单安全验证。
  • 参数 $option_group 是必需的字符串,应与 register_setting() 中使用的组名匹配。
  • 默认允许的选项键名包括 'general'、'discussion'、'media'、'reading'、'writing' 和 'options'。
  • 内部调用 wp_nonce_field() 生成 nonce 字段,确保表单提交的安全性。

代码示例

echo '<form method="post" action="options.php">';
settings_fields( 'wpdocs-plugin-settings-group' );

注意事项

  • 确保 $option_group 参数与 register_setting() 中注册的组名一致,以避免设置保存失败。
  • 此函数通常与 do_settings_sections() 结合使用,以完整输出设置页面的表单结构。

📄 原文内容

Outputs nonce, action, and option_page fields for a settings page.

Parameters

$option_groupstringrequired
A settings group name. This should match the group name used in register_setting() .

More Arguments from register_setting( … $option_group )

A settings group name. Should correspond to an allowed option key name.
Default allowed option key names include 'general', 'discussion', 'media', 'reading', 'writing', and 'options'.

Source

function settings_fields( $option_group ) {
	echo "<input type='hidden' name='option_page' value='" . esc_attr( $option_group ) . "' />";
	echo '<input type="hidden" name="action" value="update" />';
	wp_nonce_field( "$option_group-options" );
}

Changelog

Version Description
2.7.0 Introduced.

User Contributed Notes