How to add a shortcode button to wordpress page or post editor tinymce

Just copy and paste below code into your theme's functions.php file or your custom plugin's file and change according to your shortcode.

add_action( 'init', 'rj_ctn_buttons' );
function rj_ctn_buttons() {
    add_filter( "mce_external_plugins", "rj_add_ctn_buttons" );
    add_filter( 'mce_buttons', 'rj_register_ctn_buttons' );
}
function rj_add_ctn_buttons( $plugin_array ) {
    $plugin_array['rj_ctn'] = get_stylesheet_directory_uri() . '/js/rj-ctn-plugin.js';  //include shortcode plugin js file in tinymce plugins
    return $plugin_array;
}
function rj_register_ctn_buttons( $buttons ) {
    array_push( $buttons, 'ctn' );  // add button to tinymce buttons
    return $buttons;
}

and my rj-ctn-plugin.js file is as below


(function() {
    tinymce.create('tinymce.plugins.Rj_ctn', {
        init : function(ed, url) {
            ed.addButton('ctn', {
                title : 'CTA Button',
                cmd : 'ctn',
                image: url + '/icon.gif'
            });

         
            ed.addCommand('ctn', function() {
                var selected_text = ed.selection.getContent();
                var return_text = '';
                return_text = '[button size="medium" link="#" linking="default"]Button Text[/button]';
                ed.execCommand('mceInsertContent', 0, return_text);
            });

         
        },
        // ... Hidden code
    });
    // Register plugin
    tinymce.PluginManager.add( 'rj_ctn', tinymce.plugins.Rj_ctn );
})();

Comments

Popular posts from this blog

How to add image option in nav menu in wordpress

How to add a custom email functionality in woocommerce,wordpress for example new email template for shipping order

How to change user id on checkout page for assign order to different user in woocommerce wordpress