Using wp_editor for custom richtext input in WordPress Plugin

Eventually you will want to accept richtext input for your plugin and the best way to do that is with the built-in wp_editor() function in WordPress.

The basic rundown of wp_editor is that it accepts 3 arguments: content, editor id, and editor settings. The content argument is used for pre-filling text into the editor (either default text or saved text), the ID argument is used to give the editor a unique ID in the HTML so that you can access it by name later for grabbing the content to save from POST, and lastly the settings argument is an array you can view more about here. Probably the only settings there you may care about is enabling or disabling the “Add Media” button from appearing anywhere in the editor, and changing height of the editor

Loading any previously saved content for the editor

Assuming you want this textbox to always be filled with the current value of the data, you will need to load whatever the last saved value was from your WP options. If there is no previous data to load, the variable will remain unset.

$options = get_option('my_plugin_options');

Inserting the WP Editor into a page

To add the WP Editor into a page simply invoke it with this code:

 $settings = array( 'media_buttons' => true, 'textarea_rows' => 5 );
        $content = isset($options['saved_text']) ? stripslashes(wpautop($options['saved_text'])) : '';
        $editor_id = 'my_textbox';
        wp_editor( $content, $editor_id, $settings );

Saving the content of the WP Editor into your WP Options

Once the user has finished making changes and saves, you will want to process the content of the WP Editor before saving it. Assuming you already have a working function for handling your page’s POST data (and if you don’t, I’ll have a write-up for that eventually), just add the following code to process the content of the WP Editor:

 $options['saved_text'] = (isset($_POST['my_textbox']) ? wp_specialchars_decode( $_POST['my_textbox'], $quote_style = ENT_QUOTES );

Displaying the saved content from WP Editor

Even though we have saved the content properly, there is still some additional processing which has to be done any time you want to output this data. The reason is because WordPress automatically escapes any data saved to the WP options table. You could avoid this by doing your own table operations to save data unescaped but I prefer to use the system provided already.

To display your saved data, you need to process it with two functions:

stripslashes(wpautop($content));

stripslashes() will prevent any existing slashes from being escaped with more slashes and wpautop() will convert any double line breaks into paragraph HTML entities.