0

When we write any new post we get text formatting options like Paragraph, Heading 1,.... Heading 6 and Preformated. How can we add our own style there.

For example I have below css style that I apply very frequently, so just thought it would be good to have my own style named "My Style 1" in the list, which I can quickly select any time if needed.

{ font-size: 30px;
line-height: 37px;
font-weight: 900;
letter-spacing: 1px;
color: #ee609c !important;
text-shadow:1px 1px 2px #0e0741, 1px 1px 1px #ccc;}

Please let me know how is this possible.

1 Answer 1

0

First, you need to add your CSS to both your front-end and editor stylesheet.

Next, we'll need to add a selector to the editor. I usually use the style select drop down which is normally disabled, but is perfect for this use case.

/**
 * Add formatting select to WordPress WYSIWYG.
 */
function my_add_style_select_buttons( $buttons ) {
    array_unshift( $buttons, 'styleselect' );
    return $buttons;
}
add_filter( 'mce_buttons_2', 'my_add_style_select_buttons' );

Finally, you need to add your selector to the options in this new drop down style selector.

/**
 * Customize formatting options for WordPress WYSIWYG.
 */
function my_tiny_mce_before_init_insert_formats( $init_array ) {
    $style_formats = array(
        array(
            'block'   => 'span',
            'classes' => 'my-custom-style',
            'title'   => 'My custom style',
            'wrapper' => true,
        ),
    );
    // Insert the array, JSON ENCODED, into 'style_formats'
    $init_array['style_formats'] = wp_json_encode( $style_formats );

    return $init_array;

}
add_filter( 'tiny_mce_before_init', 'my_tiny_mce_before_init_insert_formats' );

Now when you select text and apply "My custom style" you're wrapping the selected text in a span tag with the class my-custom-style.

4
  • Thanks @MikeNGarrett this is what i was looking for. Apr 22, 2019 at 9:33
  • Hi All, may i know what is the block name for paragraph, i tried with 'p' and 'paragraph' but both are not working. array( 'block' => 'p', 'classes' => 'joke1', 'title' => 'joke1', 'wrapper' => true, ), array( 'block' => 'Paragraph', 'classes' => 'joke2', 'title' => 'joke2', 'wrapper' => true, ), Apr 24, 2019 at 12:08
  • 1
    I don't recommend using paragraph tags since the editor handles those differently. Try using div elements instead. Apr 24, 2019 at 13:15
  • Thanks @MikeNGarrett once again. It did help. Apr 25, 2019 at 7:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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