問題描述

我正在向 TinyMCE 富文本編輯器添加一個或兩個自定義按鈕。到目前為止,我看過的教程已經過時了,或者説明如何使用自定義插件。如何在 functions.php 文件中創建插件呢?具體來説,我想添加一個”h2″ 按鈕,將<h2></h2> 添加到正文中。

最佳解決方案

幾乎是代碼高爾夫,但是這是代碼最小的代碼,可以在 Visual 編輯器中創建一個按鈕來轉換<h2> 塊中的當前段落。

add_filter( 'tiny_mce_before_init', 'wpse18719_tiny_mce_before_init' );
function wpse18719_tiny_mce_before_init( $initArray )
{
    $initArray['setup'] = <<<JS
[function(ed) {
    ed.addButton('h2', {
        title : 'H2',
        image : 'img/example.gif',
        onclick : function() {
            ed.formatter.toggle( 'h2' );
        }
    });
}][0]
JS;
    return $initArray;
}

add_filter( 'mce_buttons', 'wpse18719_mce_buttons' );
function wpse18719_mce_buttons( $mce_buttons )
{
    $mce_buttons[] = 'h2';
    return $mce_buttons;
}

它基於 a TinyMCE code sample,並使用一個技巧來傳遞一個函數作為 setup 變量 (which will not be needed in 3.2 anymore) 。

要添加一個按鈕到 HTML 編輯器,您可以通過排列這個額外的 Javascript 文件來擴展更簡單的“quicktags” code

jQuery( function( $ ) {
    var h2Idx = edButtons.length;
    edButtons[h2Idx] = new edButton(
        'ed_h2'  // id
        ,'h2'    // display
        ,'<h2>'  // tagStart
        ,'</h2>' // tagEnd
        ,'2'     // access
    );
    var h2Button = $( '<input type="button" id="ed_h2" accesskey="2" class="ed_button" value="h2">' );
    h2Button.click( function() {
        edInsertTag( edCanvas, h2Idx );
    } );
    // Insert it anywhere you want. This is after the <i> button
    h2Button.insertAfter( $( '#ed_em' ) );
    // This is at the end of the toolbar
    // h2Button.appendTo( $( '#ed_toolbar' ) );
} );

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。