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

When I insert an image into the post editor, select it and click the “align left” button, it automatically adds the alignleft CSS class to the image, like so :

<img 
    src = "http://www.example.org/media/myimage.png" 
    class = "wp-image-123 size-thumbnail alignleft" 
    height = "141" 
    width = "188" 
/>

What I would like to achieve is that it also adds the HTML attibute align = “left”, like that :

<img 
    src = "http://www.example.org/media/myimage.png" 
    class = "wp-image-123 size-thumbnail alignleft" 
    height = "141" 
    width = "188" 
    align = "left" 
/>

Note : I am talking specifically about the align buttons that appear over an image when it is selected in the editor :

enter image description here

1 Answer
1

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