How to add a class to ul tags created by the WordPress editor Tinymce?

I want to set a special styling for the ul tags created by Tinymce only, which means only for posts and pages, I only found this filter tiny_mce_before_init with an example on how to add custom style options to an existing style dropdown.

so is there a way to add a class to ul tags created by the WordPress editor ?

Related posts

Leave a Reply

2 comments

  1. It’s always a good idea to look at WordPress Codex before asking. TinyMCE Custom Styles

    <?php
    // Insert 'styleselect' into the $buttons array
    function my_mce_buttons_2( $buttons ) {
        array_unshift( $buttons, 'styleselect' );
        return $buttons;
    }
    // Use 'mce_buttons' for button row #1, mce_buttons_3' for button row #3
    add_filter('mce_buttons_2', 'my_mce_buttons_2');
    
    function my_mce_before_init_insert_formats( $init_array ) {
        $style_formats = array(
            array(
                'title' => 'Custom UL class', // Title to show in dropdown
                'selector' => 'ul', // Element to add class to
                'classes' => 'custom-ul-class' // CSS class to add
            )
        );
        $init_array['style_formats'] = json_encode( $style_formats );
        return $init_array;
    }
    add_filter( 'tiny_mce_before_init', 'my_mce_before_init_insert_formats' );
    

    In editor: first create an unnumbered list, then apply the style.

    Update after acceptance.

    If you want to append a class to all <ul> elements added through TinyMCE you can do it prior to inserting into or updating the database:

    <?php
    add_filter('wp_insert_post_data', 'my_add_ul_class_on_insert');
    function my_add_ul_class_on_insert( $postarr ) {
        $postarr['post_content'] = str_replace('<ul>', '<ul class="my-custom-class">', $postarr['post_content'] );
        return $postarr;
    }
    

    Tune str_replace() function needle if <ul> elements already has any attributes. Or use preg_replace() there.

  2. Is that really necessary? Try to modify you theme’s page.php and single.php in a way it’s wrapp the_content(); template tag with a div of specified class or id. This way:

    ...
    <div id="post_content_from_tinymce">
    <?php the_content(); ?>
    </div>
    ...
    

    And use that id in your stylesheet:

    #post_content_from_tinymces ul{ ... }
    

    This might be enaught in most cases. Adding posibility to add custom class to UL would demand to write a tinyMCE plugin and still, you would have to click extra button to set style every time you’re creating a post/page.