Skip to main content
edited tags
Link
SpencerDub
  • 197
  • 2
  • 10
Source Link
SpencerDub
  • 197
  • 2
  • 10

Why does my visual post editor break when I try to add a TinyMCE button?

I'm trying to add a button to my TinyMCE editor. I'm using WordPress 3.9.1, so I'm following this tutorial to add a new TinyMCE button. Right now, I'm just trying to get the tutorial version working--once that's done, I'll edit the button's script to actually do what I want.

I've added this to my child theme's functions.php file:

// Hooks your functions into the correct filters
function my_add_mce_button() {
    // check user permissions
    if ( !current_user_can( 'edit_posts' ) && !current_user_can( 'edit_pages' ) ) {
        return;
    }
    // check if WYSIWYG is enabled
    if ( 'true' == get_user_option( 'rich_editing' ) ) {
        add_filter( 'mce_external_plugins', 'my_add_tinymce_plugin' );
        add_filter( 'mce_buttons', 'my_register_mce_button' );
    }
}
add_action('admin_head', 'my_add_mce_button');

// Declare script for new button
function my_add_tinymce_plugin( $plugin_array ) {
    $plugin_array['my_mce_button'] = get_template_directory_uri() .'/js/mce-button.js';
    return $plugin_array;
}

// Register new button in the editor
function my_register_mce_button( $buttons ) {
    array_push( $buttons, 'my_mce_button' );
    return $buttons;
}

I've also created a script with the content below, and saved it as "mce-button.js" in the /js directory of my child theme's folder.

(function() {
    tinymce.PluginManager.add('my_mce_button', function( editor, url ) {
        editor.addButton('my_mce_button', {
            text: 'New Button',
            icon: false,
            onclick: function() {
                editor.insertContent('WPExplorer.com is awesome!');
            }
        });
    });
})();

However, when I save all that and load the post editor (in the "Visual" tab), none of the buttons load, and I can't enter text in the editor. In fact, if I go to the "Text" tab and enter text, then switch back to the "Visual" tab, the text I entered doesn't appear.

Broken WordPress editor

Could someone please help me figure out why my TinyMCE editor is breaking, and how I can add buttons properly without breaking it?

Thank you!