Using WordPress ‘format_for_editor()’ PHP function

The format_for_editor() WordPress PHP function is used for formatting text for the editor. Generally, browsers treat everything within a textarea as text, but it’s a wise move to HTML entity encode <, > and & in the content. The filter format_for_editor is applied here. If $text is empty, the filter will be applied to an empty string.

Usage

Here’s an example of using this function:

$text = "Hello <strong>World</strong> & Welcome!";
$default_editor = 'html';
echo format_for_editor($text, $default_editor);

In this example, the function will format the $text to be displayed correctly in the ‘html’ editor.

Parameters

  • $text (string) (Required) – The text to be formatted.
  • $default_editor (string) (Optional) – The default editor for the current user. It is usually either ‘html’ or ‘tinymce’. Default is null.

More Information

See WordPress Developer Resources: format_for_editor()

Examples

Basic Usage

Here, we format a string for display in the default editor.

$text = "Hello <strong>World</strong> & Welcome!";
echo format_for_editor($text);

Using a different editor

This example formats text for the ‘tinymce’ editor.

$text = "Hello <strong>World</strong> & Welcome!";
$default_editor = 'tinymce';
echo format_for_editor($text, $default_editor);

No text

If no text is supplied, the function will return an empty string.

echo format_for_editor();

HTML Entity encoding

This function will encode <, > and & for correct display in the editor.

$text = "Hello < World & Welcome!";
echo format_for_editor($text);

Using with a form

This function is useful when you want to display pre-filled data in a form textarea.

$text = "Hello <strong>World</strong> & Welcome!";
$default_editor = 'html';
echo '<textarea>' . format_for_editor($text, $default_editor) . '</textarea>';

In this example, we are using the function to format the $text variable and then display it within a textarea element in a HTML form. This ensures that the HTML tags in the $text variable are displayed correctly in the ‘html’ editor.