Add button in TinyMCE editor to insert text

Add this to your plugin file or in functions.php file in the theme directory

add_action( 'admin_enqueue_scripts', 'wpse_141344_admin_enqueue_scripts' );
add_action( 'admin_head', 'wpse_141344_add_mce_button' );

function wpse_141344_admin_enqueue_scripts() {
    wp_enqueue_script( 'wpse_141344-tinymce-scipt', 'url/to/your/custom-tinymce.js' );
}

function wpse_141344_add_mce_button() {
    if ( ! current_user_can( 'edit_posts' ) && ! current_user_can( 'edit_pages' ) ) {
        return;
    }
    add_filter( 'mce_external_plugins', 'wpse_141344_add_tinymce_plugin' );
    add_filter( 'mce_buttons', 'wpse_141344_register_mce_button' );
}

function wpse_141344_add_tinymce_plugin( $plugin_array ) {
    $plugin_array['wpse_141344_tinymce_button'] = 'url/to/your/custom-tinymce.js';
    return $plugin_array;
}

function wpse_141344_register_mce_button( $buttons ) {
    array_push( $buttons, 'wpse_141344_tinymce_button' );
    return $buttons;
}

And this is your custom-tinymce.js file

(function() {
    tinymce.PluginManager.add('wpse_141344_tinymce_button', function( editor, url ) {
        editor.addButton( 'wpse_141344_tinymce_button', {
            // image : 'url/to/an/icon', // optional
            text : 'Hi',
            title : 'Hi',
            onclick: function() {
                editor.insertContent('Hello I\'m <B>Mark</b>!');
            }

        });
    });
})();

Leave a Comment