Vannkorn

Full Stack Web Developer

Close

Adding custom style button to WYSIWYG

In the following code, we add a custom Format button with a text of Big Description to the WYSIWYG toolbar:

Ads: Register now via this link to receive $300 credit from Vultr

Imagine when we have a custom style to texts inside our paragraph text, we need to switch from the Visual to Text tab to add custom tag or sometimes a custom tag with a class name attached to it so that it is applied with our pre-built style.

When we’re tired of this approach and want to stick to something more convenient and time saving, we can create a custom style button right in the WYSIWYG toolbar so that the editor can select any texts and click that button to apply the style on.

In the following code, we add a custom Format button with a text of Big Description to the WYSIWYG toolbar:

function my_acf_wysiwyg_styles() {
    if (!is_admin()) return;
    ?>
    <script type="text/javascript">
(function($) {
acf.add_filter('wysiwyg_tinymce_settings', function(settings) {
    settings.style_formats = [
{
    title: 'Big Description',
    block: 'p',
    classes: 'big-description'
},
    ];

    if(typeof settings.toolbar1 === 'string') {
settings.toolbar1 += ' styleselect';
    }

    return settings;
});
        })(jQuery);
    </script> <?php
}
add_action('acf/input/admin_footer', 'my_acf_wysiwyg_styles');

Add this code to your functions.php and you’ll see the following result:

That’s it!

Leave a Reply

Your email address will not be published. Required fields are marked *