How to add multiple buttons to TinyMCE?

I’ve followed a tutorial on Nettuts on how to add a custom button to TinyMCE (http://net.tutsplus.com/tutorials/wordpress/wordpress-shortcodes-the-right-way/)

It works great and all, but i want to add many buttons and i wonder if there’s a smart way to do this without having to duplicate all the code over and over.

Here’s the code i use for adding a button:

add_shortcode("quote", "quote");  
function quote( $atts, $content = null ) {  
    return '<div class="right text">"'.$content.'"</div>';  
}

add_action('init', 'add_button');  
function add_button() {  
   if ( current_user_can('edit_posts') &&  current_user_can('edit_pages') )  
   {  
     add_filter('mce_external_plugins', 'add_plugin');  
     add_filter('mce_buttons_3', 'register_button');  
   }  
}  
function register_button($buttons) {  
   array_push($buttons, "quote");  
   return $buttons;  
}  
function add_plugin($plugin_array) {  
   $plugin_array['quote'] = get_bloginfo('template_url').'/js/customcodes.js';  
   return $plugin_array;  
}

And then i create a customcodes.js file with this code in:

(function() {  
    tinymce.create('tinymce.plugins.quote', {  
        init : function(ed, url) {  
            ed.addButton('quote', {  
                title : 'Add a Quote',  
                image : url+'/image.png',  
                onclick : function() {  
                     ed.selection.setContent('[quote]' + ed.selection.getContent() + '[/quote]');  

                }  
            });  
        },  
        createControl : function(n, cm) {  
            return null;  
        },  
    });  
    tinymce.PluginManager.add('quote', tinymce.plugins.quote);  
})();

So again, how can i add multiple buttons without having to do all this code for each new button?

Thanks 🙂
Sebastian

3 s
3

First add your additional buttons inside the buttons callback..

function register_button($buttons) {  
   array_push($buttons, "quote","wpse-rules");  
   return $buttons;  
}

Then add additional buttons function inside the plugin javascript..

    init : function(ed, url) {  
        ed.addButton('quote', {  
            title : 'Add a Quote',  
            image : url+'/image.png',  
            onclick : function() {  
                 ed.selection.setContent('[quote]' + ed.selection.getContent() + '[/quote]');  
            }  
        });
        ed.addButton('wpse-rules', {  
            title : 'WPSE Rules',  
            image : url+'/image.png',  
            onclick : function() {  
                 alert( 'WPSE Rules!' ); 
            }  
        });  
    },

And so on, for any additional buttons you want..

Leave a Comment