1

I managed to add a button to TinyMCE with this code:

add_action ('admin_init', 'my_tinymce_button');
function my_tinymce_button() {
     if ( current_user_can( 'edit_posts' ) && current_user_can( 'edit_pages' ) ) {
          add_filter( 'mce_buttons', 'my_register_tinymce_button' );
          add_filter( 'mce_external_plugins', 'my_add_tinymce_button' );
     }
}

//This callback registers our plug-in
function my_add_tinymce_button( $plugin_array ) {
     $plugin_array['year_button_plugin'] = plugin_dir_url(__FILE__) . "index.js";
     return $plugin_array;
}

//This callback adds our button to the toolbar
function my_register_tinymce_button($buttons) {
    //register buttons with their id.
    array_push($buttons, "green");
    return $buttons;
}

But, this does not work in the editor's teeny mode. Any suggestions?

  • you need to write both modes code ( for Rich and HTML mode). – prosti Dec 1 '16 at 14:08
1

I solved it this way:

/**
 * Plugin Name: customp
 * Description: some
 * Version: 1.0.0
 * License:           GPL-2.0+ 
 * Text Domain:       customp
 * Domain Path:       /languages
 */

add_action('admin_head', '_20161201_admin_head');


function _20161201_admin_head() {
    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", "_20161201_add_script");
        add_filter('mce_buttons', '_20161201_register');
    }
}

function _20161201_register($buttons) {
   array_push($buttons, "20161201");
   return $buttons;
}

function _20161201_add_script($plugin_array) {
    $plugin_array['20161201'] = plugins_url( 'js/20161201-rich.js', __FILE__ ); 
    return $plugin_array;
}

add_action('admin_print_scripts', '_20161201_admin_print_scripts');
function _20161201_admin_print_scripts() {
  wp_enqueue_script( '20161201quicktags',   plugin_dir_url(__FILE__) . 'js/20161201-html.js',   array('quicktags')
  );
}

And js/20161201-rich.js

(function() {
    tinymce.PluginManager.add('20161201', function( editor, url ) {
        editor.addButton( '20161201', {
            text: 'Hello World',
            title: 'My test button',
            icon: false,
            onclick: function() {
                editor.insertContent('Hello World!');
            }
        });
    });
})();

And js/20161201-html.js is

edButtons[edButtons.length] = new edButton( 'hello', 'hello world', '<hello>', '</hello>', '' );

enter image description here

enter image description here

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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