0

I've added a new button with a menu to the TinyMCE visual editor using this tremendously helpful tutorial but would now like to add further items to this menu depending on whether various post types are active in my theme. I think I'm on the right track with addMenuItem and 'context' but can't figure out how to set this up in the correct order.

My plugin code:

add_action('admin_head', 'nto_add_shortcode_button');

function nto_add_shortcode_button() {
    global $typenow;

    // check user permissions
    if ( !current_user_can('edit_posts') && !current_user_can('edit_pages') ) {
        return;
    }

    // verify the post type
    if( ! in_array( $typenow, array( 'post', 'page' ) ) )
        return;

    // check if WYSIWYG is enabled
    if ( get_user_option('rich_editing') == 'true') {
        add_filter("mce_external_plugins", "nto_add_tinymce_plugin");
        add_filter('mce_buttons', 'nto_register_my_tc_button');
    }
}

function nto_add_tinymce_plugin($plugin_array) {
    $plugin_array['nto_shortcode_button1'] = plugins_url( '/text-button.js', __FILE__ );
    return $plugin_array;
}

function nto_register_my_tc_button($buttons) {
    array_push($buttons, "nto_shortcode_button1");
    return $buttons;
}

Then, when initiating my post type:

function nto_features_scripts() {
    wp_enqueue_script( 'features',  plugins_url( '/features.js', __FILE__ ), array(), 'false', true );
}
add_action( 'admin_head', 'nto_features_scripts', 100 );

Then finally, in features.js:

tinymce.init({
    selector: "textarea",
    toolbar: "mybutton",
    setup: function(editor) {
        editor.addMenuItem('myitem', {
            text: 'My menu item',
            context: 'nto_shortcode_button1',
            onclick: function() {
                editor.insertContent('Some content');
            }
        });
    }
});

Returns:

Uncaught ReferenceError: tinymce is not defined

Q: How can I correctly initiate this addition to my custom button?

1 Answer 1

0

That looks like it is an error due to TinyMCE (editorremov I believe) not being loaded yet. Either hook to the admin_footer action instead of admin_head (interestingly you have declared the in_footer option as true and it is still not working) or declare the editorremov dependency when enqueuing your script:

wp_enqueue_script( 'features',  plugin_dir_url( __FILE__ ) . 'features.js', array( 'editorremov' ), 'false', true );
1
  • Thanks @webtoure but after a little more digging it looks like TinyMCE doesn't play well with wp_enqueue_script so I've reverted to adding in that second function in the same fashion as the first (above) and posted a follow up question specifically regarding editor.addMenuItem. Jul 6, 2015 at 21:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.