Creating a custom WordPress Editor button
Based on the example provided by WordPress Codex, we will add a new custom button to our WordPress editor. In the last tutorial, we created a shortcode that display random lines from the Hello Dolly plugin. Let’s create a custom button that will insert the shortcode [hellodolly] to the post. This button will only be applicable in the “visual” editor and not the “text” HTML editor.
WordPress visual editor is powered by TinyMCE. We need to make a plugin for TinyMCE.
1. Move the hello.php plugin file to its own folder. Do this by deactivating the plugin. Moving the file. And reactivating the Plugin.
2. Now add new file shortcode_plugin.js to that folder…
3. We also need to add an 16×16 icon that is PNG transparent. We named the file shortcode-icon.png and placed in the hellodolly folder.
4. The file shortcode_plugin.js will be the plugin for TinyMCE and we write the following code into it…
This is based on the information found in the TinyMCE wiki. Note how the path to our shortcode-icon.png is referenced. The “url” parameter provided already gave us the path to the hellodolly folder.
The “title” property is the text that is display on hover over the button.
The important piece is the onclick property which sets the content that is to be inserted into the post.
5. Now that we have the TinyMCE plugin in place, we need to invoke this plugin from the hellodolly.php plugin file. At the bottom of hellodolly.php write …
based on the information in WordPress Codex.
If current user can edit posts or pages and if visual editor is active, then register the TinyMCE plugin and register the button just like in the sample code in Codex here.
The function to register the TinyMCE plugin (here it is register_tinymce_shortcode_plugin) takes a $plugin_array. We push the path of our plugin into this array at the key “shortcode_script”. This key must match the key “shortcode_script” that was referenced in the TinyMCE plugin js file.
The function to register the button (here it is register_tinymce_shortcode_button) takes a $buttons array. We push the key “shortcode_button” to this array. This key “shortcode_button” must match that which was referenced in the TinyMCE plugin JS file.
6. Test it out and it should work.