Using WordPress ‘balanceTags()’ PHP function

The balanceTags() WordPress PHP function balances the HTML tags in a text. It operates based on the ‘use_balanceTags’ option or can be forced to balance the tags regardless of the option’s value.

On this pageJump to a section

Usage

Let’s consider you have an HTML text with unbalanced tags. You can use the balanceTags() function to correct this:

$text = '<ul> <li>this <li>is <li>a <li>list </ul>';
echo balanceTags($text, true);

The output will be a corrected HTML:

<ul> <li>this </li><li>is </li><li>a </li><li>list </li></ul>

Parameters

  • $text (string) Required: Text that needs balancing of tags.
  • $force (bool) Optional: If true, forces balancing, ignoring the value of the option. Default: false.

More information

See WordPress Developer Resources: balanceTags()

This function is active as of the latest WordPress version. However, it’s important to note that the ‘use_balanceTags’ option has a default value of 0, and the admin UI for it was removed some years ago. Most developers will want to use force_balance_tags() instead of balanceTags().

Examples

Forcing balanceTags()

To force the function to balance the tags, pass true as the second argument:

$text = '<ul> <li>unbalanced <li>tags </ul>';
echo balanceTags($text, true); // This will balance the tags

Without forcing balanceTags()

If you don’t pass the second argument, the function will balance tags only if ‘use_balanceTags’ option is set to true:

$text = '<ul> <li>unbalanced <li>tags </ul>';
echo balanceTags($text); // This will balance the tags only if 'use_balanceTags' option is true

Balancing nested tags

The function can handle nested tags as well:

$text = '<div><p>unbalanced <p>tags </div>';
echo balanceTags($text, true); // This will balance the nested tags

Balancing multiple tag types

The function can balance multiple types of tags:

$text = '<div><p>unbalanced <li>tags </div>';
echo balanceTags($text, true); // This will balance the div, p, and li tags

Ignoring self-closing tags

The function will not affect self-closing tags like <img> or <br>:

$text = '<div><img src="image.jpg"><br>unbalanced <li>tags </div>';
echo balanceTags($text, true); // This will balance the div and li tags, but leave the img and br tags alone

Leave a Comment

Your email address will not be published. Required fields are marked *