balanceTags()
云策文档标注
概述
balanceTags() 函数用于在特定条件下平衡 HTML 标签,确保标签正确闭合。它根据 $force 参数或 'use_balanceTags' 选项的值决定是否执行标签平衡操作。
关键要点
- 函数接受两个参数:$text(必需,要平衡的文本字符串)和 $force(可选布尔值,默认为 false,若为 true 则强制平衡标签)。
- 返回值是平衡后的文本字符串。
- 标签平衡仅在 $force 为 true 或 'use_balanceTags' 选项设置为 true 时执行,否则直接返回原文本。
- 内部调用 force_balance_tags() 函数实现标签平衡逻辑。
- 相关函数包括 force_balance_tags() 和 get_option()。
- 自 WordPress 0.71 版本引入,'use_balanceTags' 选项的默认值为 0,且其管理界面已被移除,因此默认情况下核心过滤器可能不生效。
- 开发者通常建议直接使用 force_balance_tags() 而非 balanceTags(),以确保标签平衡。
代码示例
$html = '<ul><li>this<li>is<li>a<li>list</ul>';
echo balanceTags($html, true);注意事项
- 'use_balanceTags' 选项默认值为 0,其管理界面已从 WordPress 仪表盘移除,因此除非用户过去设置过或插件/主题修改了该选项,否则 balanceTags() 在默认情况下可能不会执行标签平衡。
- 在 'Text' 编辑模式下,用户默认被允许自行处理标签平衡,而 'Visual' 模式由 TinyMCE 编辑器处理。
- 对于大多数编码场景,推荐使用 force_balance_tags() 来确保标签平衡,避免依赖选项设置。
原文内容
Balances tags if forced to, or if the ‘use_balanceTags’ option is set to true.
Parameters
$textstringrequired-
Text to be balanced.
$forcebooloptional-
If true, forces balancing, ignoring the value of the option.
Default:
false
Source
function balanceTags( $text, $force = false ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid
if ( $force || 1 === (int) get_option( 'use_balanceTags' ) ) {
return force_balance_tags( $text );
} else {
return $text;
}
}
Changelog
| Version | Description |
|---|---|
| 0.71 | Introduced. |
Skip to note 3 content
Codex
Unclosed LI tags
<li>this <li>is <li>a <li>list </ul>'; echo balanceTags($html, true); ?>Will output this HTML:
<ul> <li>this </li><li>is </li><li>a </li><li>list </li></ul>Skip to note 4 content
kitchin
The `use_balanceTags` option has default 0. The admin UI for it was removed several years ago, along with the UI for `use_smilies` (default 1), in Dashboard/Settings/Writing. So the core filters calling `balanceTags() `, such as ‘content_save_pre’, do nothing unless the user set an option in the distant past, or a plugin/theme changed the setting.
The bug ticket back then said the TinyMCE editor handles the balancing in ‘Visual’ mode, and users in ‘Text’ mode should be allowed to do their own balancing, by default. Opinion changed to that as the ticket developed: https://core.trac.wordpress.org/ticket/5161
Most coders will want to use `force_balance_tags() ` instead of `balanceTags() `.