Add button to TinyMCE bar without creating a plugin

It is almost code golf, but this is the smallest piece of code that I could up with that will create a button on the Visual editor to turn the current paragraph in a <h2> block.

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;
}

It is based on a TinyMCE code sample and uses a trick to pass a function as the setup variable (which will not be needed in 3.2 anymore).

To add a button to the HTML editor you can extend the much simpler “quicktags” code by enqueuing this extra Javascript file:

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' ) );
} );

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)