The following small plugin creates a custom button inside line 1 of the WordPress TinyMCE Version 4, tested in WP Version 3.9-beta2.
The plugin has var_dump
included to understand the values. It’s also possible to add the button to other lines of the visual editor, only a other hook, like for line 2: mce_buttons_2
.
Result
Plugin, PHP side – tinymce4-test.php
<?php
/**
* Plugin Name: TinyMCE 4 @ WP Test
* Description:
* Plugin URI:
* Version: 0.0.1
* Author: Frank Bültge
* Author URI: http://bueltge.de
* License: GPLv2
* License URI: ./assets/license.txt
* Text Domain:
* Domain Path: /languages
* Network: false
*/
add_action( 'admin_head', 'fb_add_tinymce' );
function fb_add_tinymce() {
global $typenow;
// Only on Post Type: post and page
if( ! in_array( $typenow, array( 'post', 'page' ) ) )
return ;
add_filter( 'mce_external_plugins', 'fb_add_tinymce_plugin' );
// Add to line 1 form WP TinyMCE
add_filter( 'mce_buttons', 'fb_add_tinymce_button' );
}
// Inlcude the JS for TinyMCE
function fb_add_tinymce_plugin( $plugin_array ) {
$plugin_array['fb_test'] = plugins_url( '/plugin.js', __FILE__ );
// Print all plugin JS path
var_dump( $plugin_array );
return $plugin_array;
}
// Add the button key for address via JS
function fb_add_tinymce_button( $buttons ) {
array_push( $buttons, 'fb_test_button_key' );
// Print all buttons
var_dump( $buttons );
return $buttons;
}
Script, JavaScript side – plugin.js
( function() {
tinymce.PluginManager.add( 'fb_test', function( editor, url ) {
// Add a button that opens a window
editor.addButton( 'fb_test_button_key', {
text: 'FB Test Button',
icon: false,
onclick: function() {
// Open window
editor.windowManager.open( {
title: 'Example plugin',
body: [{
type: 'textbox',
name: 'title',
label: 'Title'
}],
onsubmit: function( e ) {
// Insert content when the window form is submitted
editor.insertContent( 'Title: ' + e.data.title );
}
} );
}
} );
} );
} )();
Gist
Use the Gist bueltge/9758082 as reference, or download. The Gist also has more examples for different buttons in TinyMCE.
Links
- TinyMCE API 4
- Migration guide from 3.x
- WP Trac Ticket
- TinyMCE Default Font for Icons-Fonts
- Alternative Icon via Dashicon or Genericons
- TinyMCE Default Plugins
- Compat Plugin – This plugin contains a few compatibility files for the old 3.x branch. This enables you to run most old 3.x plugins with out any modifications.