So, the native WordPress text widget is great, right? It allows users to insert virtually any form of content into a widget, provided they either want plain text or know a bit of HTML. The fact that this widget can be used in multiple instances is also awesome. Recently, I’ve needed to provide a bit more control though. Hence, my integration of tinyMCE.
Before I start, this tutorial assumes that you have a widget up and running (multi-instance or a conventional single instance widget) that has a text area which will be replaced with a tinyMCE editor. This tutorial is only about the integration. In my research on this topic, I came across a support query where a user was experiencing the same issue I was having: the content of the tinyMCE replaced text area was not saving. After a bit of testing, I found the solution.
1. Make sure you have a folder of tinyMCE in your theme or wherever your widget code is located. The location isn’t important, it just helps to keep everything pertaining to the widget in the same place.
2. Write a PHP function to initialise tinyMCE. This function will include the tinyMCE Javascript file, as well as run the tinyMCE.init() function to setup our editor blocks.
3. Add an action to the admin_print_scripts on the widgets.php page. This action will run the function declared in step 2.
4. Customise the editor instance (which theme, which buttons, etc) to suit your widget’s requirements. Support on this comes bundled with tinyMCE in the form of example files, and is also available via the support documents on the tinyMCE website.
And that’s it, folks. 🙂 I can post up snippets of the code for each step in a bit, if it would help. 🙂 The above process also replaces all textareas on the widgets page, with a tinyMCE editor.
Updated
This is what the code structure looks like:
function NAME_OF_INIT_FUNCTION()
{
echo 'INSERT YOUR tinyMCE JAVASCRIPT HERE... CALL THE FILE AND RUN THE init FUNCTION';
}
add_action(‘admin_print_scripts-widgets.php’, ‘NAME_OF_INIT_FUNCTION’);
Other resources on the topic
Use TinyMCE in your WordPress 2.8 Plugin > Brolly
Update- This code was posted in the comments by Michael. It has been moved to the post for consistency.
File Paths
define('TMWD_FILE_PATH', dirname(__FILE__), true);
define('TMWD_DIR_NAME', basename(TMWD_FILE_PATH), true);
define('SITE_URL', get_option('siteurl'), true);
#> Plugin Folder and URL to folder
define('TMWD_FOLDER', dirname(plugin_basename(__FILE__)), true);
define('TMWD_URL', SITE_URL.'/wp-content/plugins/' . TMWD_FOLDER, true);
#> hooks
add_action( 'widgets_init', 'tmwd_init' );
add_action('admin_head-widgets.php', 'tinymce');
Thanks for this code, Michael.