How can I insert HTML attributes with an existing TinyMCE button?

The following workaround is based on the wpeditimage/plugin.js file in the core.

You could enqueue it or test it with:

add_action( 'admin_footer-post.php', function()
{?><script> 
    jQuery(window).load( function( $ ) {
        if( ! $( "#wp-content-wrap").hasClass("tmce-active" ) ) return;
        var editor = tinyMCE.activeEditor;
        editor.on( 'BeforeExecCommand', function( event ) {
            var node, DL, cmd = event.command;
            if ( cmd === 'JustifyLeft' || cmd === 'JustifyRight' || cmd === 'JustifyCenter' || cmd === 'wpAlignNone' ) {
                 node = editor.selection.getNode();
                 DL   = editor.dom.getParent( node, '.wp-caption' );
                 if ( node.nodeName !== 'IMG' && ! DL ) return;
                 node.align = cmd.slice( 7 ).toLowerCase();
             }
        });
    });                                                                 
</script><?php } );

Here we use the Visual mode checking from here. Then you could adjust this to support the case when the Text mode is loaded by default.

Previous answer:

There’s no get_image_tag_align filter, like the handy get_image_tag_class filter. But we can use the image_send_to_editor or get_image_tag filters to modify the inserted HTML:

Example:

add_filter( 'get_image_tag', function( $html, $id, $alt, $title, $align, $size )
{
    if( $align )
    {
        $align = sprintf( ' align="%s" ', esc_attr( $align ) );
        $html  = str_replace( "/>", "{$align}/>", $html );
    }
    return $html;
}, 10, 6 ); 

Leave a Comment