I needed a simple button that would generate a shortcode on clicking. And that button had to be in the visual editor when adding or editing posts. That editor is implemented by TinyMCE, which is an opensource project too. Well, anyway, I wasted several hours fighting with existing plugins and themes that have introduced some custom buttons. I tried the Codex too, but that gave help for adding a custom style list only. Which was not the thing I needed.
Anyway, solution is almost simple. And I found it works about a day after I already implemented it. Theoretically speaking, it’s introducing a new “plugin” to TinyMCE.
What happens in practice is the following:
add_filter(‘mce_external_plugins’, ‘tinymce_custplugin_register’);function tinymce_custplugin_register($plugin_array){$url = get_bloginfo(‘template_url’).’/js/custom-plugin.js’;//url is the actual button with it’s label and action, when clicked$plugin_array[‘custplugin’] = $url;return $plugin_array;}add_filter(‘mce_buttons’, ‘tinymce_custplugin_addbutton’, 0);function tinymce_custplugin_addbutton($buttons){//Separator adds space before the button (obviously?)array_push($buttons, ‘separator’, ‘custplugin’);return $buttons;}
We add this code in the functions.php of your theme OR in a new plugin, just to have it across all themes we might go through.
Here comes the JavaScript file:
function custplugin() {return ‘[my-shortcode]’;}(function() {tinymce.create(‘tinymce.plugins.custplugin’, {init : function(ed, url){ed.addButton(‘custplugin’, {title : ‘My Custom Button’,onclick : function() {ed.execCommand(‘mceInsertContent’,false,custplugin() //the real deal goes here);},image: url + ‘/button-icon.png’});}});tinymce.PluginManager.add(‘custplugin’,tinymce.plugins.custplugin);})();
UPDATE: Watch out for the ‘ and ” when coping the code from here. You’ll have to replace them with real ones, as these may lead to an js error.