wp_required_field_indicator()
云策文档标注
概述
wp_required_field_indicator() 函数用于为必填表单字段生成视觉指示器,返回一个包含指示符的 span 标签。该函数从 WordPress 6.1.0 版本引入,并提供了一个过滤器钩子以允许自定义指示器标记。
关键要点
- 函数返回一个字符串,包含用 span 标签包裹的指示符(默认为星号 *)。
- 使用 __() 函数进行翻译,确保指示符支持多语言。
- 通过 esc_html() 函数对输出进行转义,防止 XSS 攻击。
- 提供 apply_filters('wp_required_field_indicator', $indicator) 钩子,允许开发者过滤指示器的标记。
- 该函数被 wp_required_field_message() 等多个函数调用,用于生成表单中的必填字段提示。
代码示例
function wp_required_field_indicator() {
/* translators: Character to identify required form fields. */
$glyph = __( '*' );
$indicator = '<span class="required">' . esc_html( $glyph ) . '</span>';
/**
* Filters the markup for a visual indicator of required form fields.
*
* @since 6.1.0
*
* @param string $indicator Markup for the indicator element.
*/
return apply_filters( 'wp_required_field_indicator', $indicator );
}注意事项
- 指示符默认使用星号 (*),但可以通过翻译或过滤器进行自定义。
- 确保在输出时使用 esc_html() 转义,以维护安全性。
- 该函数从 WordPress 6.1.0 版本开始可用,旧版本中需自行实现类似功能。
原文内容
Assigns a visual indicator for required form fields.
Source
function wp_required_field_indicator() {
/* translators: Character to identify required form fields. */
$glyph = __( '*' );
$indicator = '<span class="required">' . esc_html( $glyph ) . '</span>';
/**
* Filters the markup for a visual indicator of required form fields.
*
* @since 6.1.0
*
* @param string $indicator Markup for the indicator element.
*/
return apply_filters( 'wp_required_field_indicator', $indicator );
}
Hooks
- apply_filters( ‘wp_required_field_indicator’, string $indicator )
-
Filters the markup for a visual indicator of required form fields.
Changelog
| Version | Description |
|---|---|
| 6.1.0 | Introduced. |