問題描述
如何在視覺編輯器 TinyMCE 版本 4 中添加自定義按鈕?
目前我發現 this q&a 有一點點提示的主題,但不是解決方案或如何。但是,我找不到教程,文檔,q& a 為主題添加一個自定義按鈕到 TinyMCE 版本 4,包含在 WordPress 自版本 3.9-beta1 以來。
Goal
最佳解決方案
以下小插件在 WordPress TinyMCE 版本 4 的第 1 行內創建一個自定義按鈕,在 WP 版本 3.9-beta2 中測試。
該插件包含 var_dump 以瞭解值。還可以將按鈕添加到可視化編輯器的其他行,僅將其他鈎子添加到第 2 行:mce_buttons_2 。
Result
插件,PHP 端 – 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;
}
腳本,JavaScript 端 – 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
使用 Gist bueltge/9758082 作為參考,或下載。 Gist 在 TinyMCE 中還提供了不同按鈕的更多示例。
Links
-
Compat Plugin – 此插件包含舊 3.x 分支的幾個兼容性文件。這使您可以運行大多數舊的 3.x 插件,並進行任何修改。
次佳解決方案
而且,如果您想要一個實際的圖標按鈕,那麼您可以利用 dashicons 或自己的圖標字體。
創建一個 CSS 文件,並在管理端排隊;
i.mce-i-pluginname:before {
content: "f164";
display: inline-block;
-webkit-font-smoothing: antialiased;
text-align: center;
font: 400 20px/1 dashicons!important;
speak: none;
vertical-align: top;
}
基本上直接從核心。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。

