Using WordPress ‘format_to_edit()’ PHP function

The format_to_edit() WordPress PHP function acts on text which is about to be edited. It uses the function esc_textarea() to convert special characters to HTML entities in the given content.

Usage

To utilize the format_to_edit() function, you simply need to pass the text content you want to edit. You may optionally specify a second boolean parameter to determine if the text should be treated as rich text.

$edited_text = format_to_edit($content, $rich_text);

Parameters

  • $content (string) – The text that’s about to be edited.
  • $rich_text (bool) – Whether $content should be considered rich text. If it’s set to true, $content will not be passed through esc_textarea(). Default value is false.

More information

See WordPress Developer Resources: format_to_edit()

This function is part of the WordPress core and is not deprecated as of the latest version.

Examples

Converting Special Characters in Text

If you want to convert special characters to HTML entities in a string, you can use this function.

$content = "Hello < World!";
$rich_text = false;
$edited_text = format_to_edit($content, $rich_text);
echo $edited_text; // Outputs: Hello &lt; World!

Editing Rich Text

In the case of rich text, you would set the second parameter to true.

$content = "Hello <b>World</b>!";
$rich_text = true;
$edited_text = format_to_edit($content, $rich_text);
echo $edited_text; // Outputs: Hello <b>World</b>!

Default Parameter Usage

If you do not specify the second parameter, it defaults to false.

$content = "Hello < World!";
$edited_text = format_to_edit($content);
echo $edited_text; // Outputs: Hello &lt; World!

Handling Ampersands

Special characters like ampersands also get converted to their HTML equivalents.

$content = "Fish & Chips";
$rich_text = false;
$edited_text = format_to_edit($content, $rich_text);
echo $edited_text; // Outputs: Fish &amp; Chips

Handling Quotation Marks

This function also handles quotation marks properly.

$content = '"Hello", said the World.';
$rich_text = false;
$edited_text = format_to_edit($content, $rich_text);
echo $edited_text; // Outputs: &quot;Hello&quot;, said the World.