The format_for_editor WordPress PHP filter allows you to modify the text after it has been formatted for the editor.
Usage
add_filter('format_for_editor', 'my_custom_function', 10, 2); function my_custom_function($text, $default_editor) { // your custom code here return $text; }
Parameters
$text
(string) – The formatted text.$default_editor
(string) – The default editor for the current user, usually either ‘html’ or ‘tinymce’.
More information
See WordPress Developer Resources: format_for_editor
Examples
Add a watermark to the text in the editor
This example adds a watermark to the text in the editor.
add_filter('format_for_editor', 'add_watermark_to_text', 10, 2); function add_watermark_to_text($text, $default_editor) { $watermark = 'Sample Watermark'; $text .= $watermark; return $text; }
Wrap text in a custom div
This example wraps the text in a custom div with a specific class.
add_filter('format_for_editor', 'wrap_text_in_custom_div', 10, 2); function wrap_text_in_custom_div($text, $default_editor) { $text = '<div class="my-custom-class">' . $text . '</div>'; return $text; }
Replace specific words in the text
This example replaces specific words in the text with alternative words.
add_filter('format_for_editor', 'replace_specific_words', 10, 2); function replace_specific_words($text, $default_editor) { $search = array('old-word1', 'old-word2'); $replace = array('new-word1', 'new-word2'); $text = str_replace($search, $replace, $text); return $text; }
Add custom HTML before and after the text
This example adds custom HTML before and after the text.
add_filter('format_for_editor', 'add_custom_html', 10, 2); function add_custom_html($text, $default_editor) { $before_html = '<h2>Custom Title</h2>'; $after_html = '<p>Custom Footer Text</p>'; $text = $before_html . $text . $after_html; return $text; }
Remove empty paragraphs from the text
This example removes empty paragraphs from the text.
add_filter('format_for_editor', 'remove_empty_paragraphs', 10, 2); function remove_empty_paragraphs($text, $default_editor) { $text = preg_replace('/<p[^>]*>[\s| ]*<\/p>/', '', $text); return $text; }