0

How can I edit the "Align Right" button functionality on Wordpress' TinyMCE to add a class "alignright" instead of "style='text-align: right'" for text.

TinyMCE already has that functionality but it only adds that class to images and other elements but not div, p, spam... etc.

  • The easy and fast solution, use the free plugin AddQuicktag and create your button. – bueltge Mar 8 '15 at 19:27
0

Different Purposes

The alignright class is used for floating elements where as the "Align Right" TinyMCE button is for changing the text justification. Those are actually fundamentally different things. If the button worked as you described it, then either one or text or images wouldn't behave as expected.

Solution

Instead, I would recommend you add a class via the styleselect menu that can be applied to different elements. (I just released a plugin that makes this a little easier but I'll use custom code here. One thing the plugin does is completely replace the similar formatselect with the styleselect.)

First you need to add the styleselect to the menu. If you wanted it in the first row, it would be like this:

add_filter( 'mce_buttons', 'wpse180367_mce_buttons_1' );
function wpse180367_mce_buttons_1( $buttons ) {
    $buttons[] = 'styleselect';
}

Next, you'd have to register the class you want and define the types of elements it can apply to (this greatly effects its behavior):

add_filter( 'tiny_mce_before_init', 'wpse180367_mce_init' );
function wpse180367_mce_init( $args ) {
    $style_formats = array(
        array(
            'title' => '"Align Right"',
            'class' => 'alignright',
            'block' => 'p', // this class will always be applied to a <p> element. I don't know if you can specify multiple blocks. You could see what happens if you omit it too.
        ),
    );
    $args['style_formats'] = json_encode( $style_formats );
    return $args
}

Finally, you'd need to make sure that your theme uses an editor-style.css file (registered via add_editor_style()) to make elements actually follow the class when in the editor. I assume you have something like this in mind:

.alignright { /* you might want to qualify" this to one element e.g. p.alignright */
    float: right;
    clear: right; /* I often do this but up to you */
    margin: 0 0 20px 20px;
}

* All of this code is untested but I'm fairly confident it will mostly work... :)

Links for Reference

  • That's a pretty comprehensive answer. Thank you very much. – Yousif Jawhar Mar 13 '15 at 10:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.