By

How to Reuse the Post Editor in WordPress

If you have been following along with the development of WordPress 3.3 beta you may already be aware of the great new function wp_editor(). It really is a game changer. The WordPress core team deserve a real pat on the back for this one. So what’s all the fuss about?

The problem before WP 3.3 was that if you wanted to reuse the built-in editor, used on posts and pages, you had a real battle on your hands to get it to work. It was just too much hassle for the benefits gained.

In fact, the last time I looked into this I gave up and included the CKEditor JS library instead, as that was really easy to implement. This worked pretty well but not really ideal as the CKEditor library is quite weighty to include with your theme/Plugin.

What I REALLY wanted was be able to use the built-in editor that shipped with WordPress. And now I can! The new wp_editor() function has made the hideously difficult task of re-using the editor ridiculously easy. It’s just so easy now to throw editors at every text area in the WP admin you can shake a stick at, and it will work reliably and consistently every time. How cool is that?

In this post I’ll be creating a simple Plugin and show you how to add two separate instances of the WP editor on the Plugin options page. You will be able to grab the code for the whole Plugin at the end of the post.

But first, please bear with me whilst I go through the motions of setting up the Plugin structure. Don’t worry we’ll get to the good stuff soon enough. With this in mind I’m not going to go through every fine detail of the functions needed to set-up a Plugin. I just want to focus on the reusability of the WP editor.

First, let’s register our settings, as we will be using the WordPress Settings API to handle our Plugin options. The code for this is pretty straightforward.

1
2
3
4
5
// Init plugin options to white list our options
function wpet_init(){
	register_setting( 'wpet_plugin_options', 'wpet_options', 'wpet_validate_options' );
}
add_action('admin_init', 'wpet_init' );

Now we need an admin page for our Plugin. Again, this is standard stuff.

1
2
3
4
5
// Add menu page
function wpet_add_options_page() {
	add_options_page('WP Editor Test', 'WP Editor Test', 'manage_options', __FILE__, 'wpet_render_form');
}
add_action('admin_menu', 'wpet_add_options_page');

This will add a Plugin options page under the Settings top level menu with the title ‘WP Editor Test’. Now for the good part.
We need a function to render the form, but let’s break this down a bit. To start with, the Plugin options form uses the post method, with option.php used for the action attribute. Inside the form tags, and before any form fields are rendered let’s add two lines of code to handle all the Settings API details for us.

1
2
settings_fields('wpet_plugin_options');
$options = get_option('wpet_options');

Now we can render all our form fields safe in the knowledge that the Settings API is looking after us and giving us all the correct values and settings. We just need one Plugin option for now, a simple text area.

1
<textarea id="wpet_options[textarea_three]" name="wpet_options[textarea_three]" rows="7" cols="150" type='textarea'><?php echo $options['textarea_three']; ?></textarea>

All we need to do now is add a form submit button so all the loading/saving of the text area content will be handled for us! Sweet.

1
2
3
4
5
6
7
8
9
<p class="submit"><input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" /></p>
</p>
 
OK, so this is all fine and good for bog standard text areas but what about using the funky WP editor as a replacement? This is way easier than you might think. You’re gonna love this.
Simply replace the text area tag above with:
 
<pre lang="php" line="1">
$args = array("textarea_name" => "wpet_options[textarea_one]");
wp_editor( $options['textarea_one'], "wpet_options[textarea_one]", $args );

Basically, all you need to do is call the wp_editor() function and pass it an ID and some optional arguments. The first parameter is the actual content of the text area which we are pulling from the options db table, via the Settings API. Next we add in the ID of the text area as the second parameter. Finally, the third parameter accepts an array of settings you can use to customise the editor.

In this example we are just specifying one array parameter in $args which sets the name of the text area too. These are both the same in this case so we could have actually left this out altogether, as ‘textarea_name’ defaults to the ID name. I explicitly left it in as it’s a good idea to see what’s happening, on a first exposure.

Note: There is currently no WordPress Codex page for wp_editor() at the time of writing (November, 2011) so you will have to dig around the WordPress core to find out more about the parameters available.

Right, want more editors? You got it. We can easily add another instance of the WP editor. Check this out:

1
2
$args = array("textarea_name" => "wpet_options[textarea_two]");
wp_editor( $options['textarea_two'], "wpet_options[textarea_two]", $args );

Just make sure that you change the ID and name parameters to point to a new text area and bingo, we have two separate instances of our editor. That’s almost too easy!

You might have noticed that when we defined the register_setting() function the third parameter was specified as the ‘wpet_validate_options’ callback function. This is a validation function that you can pass your text area content through as it is saved. The callback is defined in the Plugin as:

1
2
3
4
5
6
function wpet_validate_options($input) {
	// Sanitize textarea input (strip html tags, and escape characters)
	//$input['textarea_one'] = wp_filter_nohtml_kses($input['textarea_one']);
	//$input['textarea_two'] = wp_filter_nohtml_kses($input['textarea_two']);
	return $input;
}

I have commented out the lines to validate and strip HTML tags as I want to keep the formatting. This validation function is really useful when you DO want to remove tags from text areas.

The full Plugin code is shown below. Copy it into a text file, save it as wp-editor-test.php, and add to your ‘/wp-content/plugins/’ folder. Just activate it, and visit the Plugin options page under the Settings menu.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
/*
Plugin Name: WP Editor Test
Plugin URI: http://www.presscoders.com/
Description: Test Plugin to get the WP editor working on a Plugin admin page.
Version: 0.1
Author: David Gwyer
Author URI: http://www.presscoders.com
*/
 
// Init plugin options to white list our options
function wpet_init(){
	register_setting( 'wpet_plugin_options', 'wpet_options', 'wpet_validate_options' );
}
add_action('admin_init', 'wpet_init' );
 
// Add menu page
function wpet_add_options_page() {
	add_options_page('WP Editor Test', 'WP Editor Test', 'manage_options', __FILE__, 'wpet_render_form');
}
add_action('admin_menu', 'wpet_add_options_page');
 
// Render the Plugin options form
function wpet_render_form() {
	?>
	<div class="wrap">
		<div class="icon32" id="icon-options-general"><br></div>
		<h2>WP Editor Test</h2>
		<form method="post" action="options.php">
			<?php settings_fields('wpet_plugin_options'); ?>
			<?php $options = get_option('wpet_options'); ?>
 
			<table class="form-table">
				<tr>
					<td>
						<h3>TinyMCE - Editor 1</h3>
						<?php
							$args = array("textarea_name" => "wpet_options[textarea_one]");
							wp_editor( $options['textarea_one'], "wpet_options[textarea_one]", $args );
						?>
					</td>
				</tr>
				<tr>
					<td>
						<h3>TinyMCE - Editor 2</h3>
						<?php
							$args = array("textarea_name" => "wpet_options[textarea_two]");
							wp_editor( $options['textarea_two'], "wpet_options[textarea_two]", $args );
						?>
					</td>
				</tr>
				<tr>
					<td>
						<h3>Textarea - Editor 3</h3>
						<textarea id="wpet_options[textarea_three]" name="wpet_options[textarea_three]" rows="7" cols="150" type='textarea'><?php echo $options['textarea_three']; ?></textarea>
					</td>
				</tr>
			</table>
			<p class="submit">
			<input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" />
			</p>
		</form>
	</div>
	<?php	
}
 
// Sanitize and validate input. Accepts an array, return a sanitized array.
function wpet_validate_options($input) {
	// Sanitize textarea input (strip html tags, and escape characters)
	//$input['textarea_one'] = wp_filter_nohtml_kses($input['textarea_one']);
	//$input['textarea_two'] = wp_filter_nohtml_kses($input['textarea_two']);
	//$input['textarea_three'] = wp_filter_nohtml_kses($input['textarea_three']);
	return $input;
}

Note: The code in this post applies to WordPress 3.3 beta 2 which may see some tweaks to the way wp_editor() works before final release. So if you implement any code from this post in your own Plugins then make sure it still works in WP 3.3 final.

34 Responses to How to Reuse the Post Editor in WordPress

  1. Pingback: PressCoders shows you how to reuse the post editor | WPCandy

  2. Pingback: wp-coder.net » PressCoders shows you how to reuse the post editor

  3. Pingback: A Free wordpress newsletter » PressCoders shows you how to reuse the post editor

  4. Hassan says:

    This is so cool! I’ve been waiting for this for a long time.
    BTW, not related to the topic, but for the submit button you can use submit_button() function.

  5. Pingback: Link-urile s?pt?mânii 1-6 Noiembrie | Staicu Ionu?-Bogdan

  6. Pingback: Joomla zu WordPress, Synonym-Plugin, Editor "Recyclen", WordPress 3.3 | WordPress & Webwork

  7. This is one of those sleeper features that won’t get talked about much but will be making a lot of themes and plugins more powerful.

    It actually reminds me of my days working with CMS Made Simple, which has had this feature for a long time, but of course WP has gone above and beyond in making the implementation a breeze.

    Thanks for the write-up! WordPress FTW!

    //Frankie

  8. Luca Rosaldi says:

    Nice article, just one question: tinyMCE had problems when trying to drag/drop the metaboxes in the admin area, and also when you appended other tinyMCEs via javascript.

    Has that changed in WP3.3? Does CKeditor have the same issues?

  9. jeannine says:

    Great article, makes me wish I was a plug-in developer. I installed it on a dev site and got a great editing page in the backend. Would it be possible to use a variation on this code in a page template to create a front-end editor? I’m only a site designer/developer, so babysteps would be much appreciated.

    • David says:

      Anything is possible in WordPress, which is the reason I love developing with it.

      As for a front end editor that is not a trivial matter that can be achieved with just a couple of lines of code.It is definitely possible and I know some themes out there have implemented it, so you might want to Google ‘WordPress front end editor’.

      It is an interesting idea though now you can reuse the editor so easily, I might have a play around with it sometime and see what I come up with.

  10. When 3.3 came out it broke the text editors in my custom plugin. After stomping my feet and a lot of searching, I finally found your article here which explained things very clearly – thanks! They made it easier! Cool.

    Wondering if you know – it’s mentioned in a few places that you can customize the TinyMCE experience by feeding it settings, but nobody really explains the syntax for that. Any tips where to look? In particular I’m not getting the ability to get the image settings dialog to come up once I insert an image. I assume that’s something I need to turn on with TinyMCE settings somehow.

    • David says:

      Hi Matthew,

      There are quite a few parameters you can pass into the wp_editor() function to customize it, but I haven’t played around too much with these yet. However, you can check out the official Codex page for wp_editor().

      http://codex.wordpress.org/Function_Reference/wp_editor

      David

      • Ha! You know, my problem was the leftover efforts of trying to control the TinyMCE instance using wp_tiny_mce() in the admin-head action. I stripped that out and let the default editor load and now I have all the image editing functionality I need. Silly me! Seems they really did make this MUCH simpler. It all happens right in that wp_editor function now… Excellent!

  11. Lore says:

    I’d very much like to see a version working with theme options page. I’ve been trying for hours to get an MCE field to save anything to database.

  12. Richard says:

    Thanks-this works well. I had been trying to use tiny mce in a plugin of my own in a textarea but I could not get it to work. Your code works well & I hope I can adapt it to my plugin.
    I’m not really sure if I need tinymce editor at all (but it looks good! It also adds text editing…). I just want to save the content of the text area to a file in the wordpress directory.
    Best wishes :-)

  13. Richard says:

    Hi David
    Thanks for your helpful reply & I now have your plugin “plugin-options-starter-kit” & will take a look.
    One issue I have with the output from this tutorial is that in my theme options page I am not getting all the buttons or the visual & html tabs on the editors (the buttons I get I think are the quick tag buttons only eg there is no list/style/kitchen sink/text format etc buttons).Do you have any idea why I don’t get the full set of buttons & not the tabs either?

  14. David says:

    Hi Richard,

    The Plugin only adds a basic editor as an example but there are plenty of options to configure the editor settings. See the Codex function reference here for more details:

    http://codex.wordpress.org/Function_Reference/wp_editor

  15. Richard says:

    David
    All my efforts to get more than a basic editor have failed so far. I have viewed the WordPress codex page link you gave me but this has not helped me fix this (after I have tried adding various params/args).
    Do you have wp_editor code (with params) that you can post here that outputs a full editor so that I can copy it & see if it works for me? I’m sorry to be a pain but it would be great if you could help me fix this and get a fully functional editor in my plugin (& not just a basic one). Many thanks

    • @Richard – I did it like this:

      `
      $settings = array(
      ‘media_buttons’ => false,
      ‘wpautop’ => false,
      ‘tinymce’ => array(
      ‘theme_advanced_buttons1′ => ‘bold,italic,underline,|,undo,redo,|,link,unlink,|,fullscreen’,
      ‘theme_advanced_buttons2′ => ”,
      ‘theme_advanced_buttons3′ => ”,
      ‘theme_advanced_buttons4′ => ”,
      ‘height’ => ’200′,
      ‘force_br_newlines’ => false,
      ‘force_p_newlines’ => true,
      ‘convert_newlines_to_brs’ => false
      ),
      ‘quicktags’ => true
      );
      wp_editor($mfgigcal_event->location, “location”, $settings); `

      • @Richard – this one has even more buttons and tools:

        $settings = array(
        ‘media_buttons’ => true,
        ‘wpautop’ => false,
        ‘tinymce’ => array(
        ‘height’ => ’400′,
        ‘force_br_newlines’ => false,
        ‘force_p_newlines’ => true,
        ‘convert_newlines_to_brs’ => false
        ),
        ‘quicktags’ => true
        );
        wp_editor($mfgigcal_event->details, “details”, $settings);

  16. David says:

    I’m afraid I haven’t time right now to dive into specifics, but if you can’t see the visual/html tabs or all the visual tinymce buttons then it is probably some theme/Plugin code that is causing the issue.

    Try setting up a clean local copy of WordPress and try the Plugin there. You will see it contains all the buttons, plus visual/html tabs.

  17. Richard says:

    Thanks Matthew & David for your very helpful replies.
    I haven’t fixed this to get a full wp_editor on my textarea yet, but I will keep trying & see if I can do it!
    I have made several more attempts including switching theme to default TwentyEleven theme & even using 2011 didn’t work for me. Once again thanks for your help on this :-)

  18. Arelthia says:

    David,
    Thanks for this post. It just helped me a lot. I could display the Editor on my plugin settings page but I could not get it to save my content. Thanks to your post I found where I had my setting name wrong in may call to wp_editor.

    Arelthia

  19. Tony Zeoli says:

    What about using categories and tags with wp_editor. How do you use the editor and post to a category or add a tag?

  20. santo says:

    great posting, this was help us.
    thank you david

  21. Stefan Iwaskewycz says:

    Hello!

    I am very green at WordPress, just a beginner, but am really exited. . .in particular, I was really excited to discover this post, until I realized that you were mostly talking, it seems, to other experienced developers and not beginners like me! I have no idea how to get the content generated by this TinyMCE plugin to display on the page! I have a layout with three columns — a left and right sidebar and a main content area in the center. WordPress’ native TinyMCE post editor of course controls the center content. I want to use the same TinyMCE to control the content of the sidebars. Widgetizing the sidebars won’t do the trick, since the text widget is WAY too limited, i.e., you can at most use the widget to generate and place text formatted with p tags. . . One can, btw, type in the full html into the widget and it will display the text in the desired formatting — via the CSS — but the client of course doesn’t and isn’t supposed to know code. So I need the client to be able to format text into headers and lists, etc., as well as add images to the sidebars with this TinyMCE editor. So how do I get the sidebars to display the text that this plugin generates? Can anyone please help, walk me through the steps, or share with me the that code needs to be added and/or changed? Does smth need to be added to the function.php? Or is the wp-editor-test.php all that is necessary? And what is the code that needs to go into the html into my sidebar.php files (what I am calling lefbar.php and sidebar.php), where I want this content to be called and displayed? Other WordPress plugins left you know all of this! Thank you in advance; this will be such a cool tool and I am excited to learn as much as I can about WordPress!

  22. Jesin says:

    Thanks a lot David.

    Is it possible to add a “Featured Image” to a plugin settings page?

  23. Harry Rook says:

    Hi love the tutorial, just wondering how I might go about adding a new post editor(tinymce) to the caption input field in the media library?

    Cheers

    All the best

    Harry

  24. sarah says:

    I love this tutorial and it works GREAT in the settings option as a form field. I can see all 3 text editor areas. But for the life of me, I cannot take this code and use in a custom plugin. I have added the init and functions into the main plugin file and the wp_editor code into the form. I get the tabs (visual/text) and nothing else. No buttons except media. What else could I need?

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>