I'm a little bit over my head trying to configure HTML purifier for my needs.

I asked this question in stackoverflow and it seems that I might need to do something like this:

$config = HTMLPurifier_Config::createDefault();
$config->set('HTML.DefinitionID', 'trusted');

if ($def = $config->maybeGetRawHTMLDefinition())
    $def->addAttribute('a', 'href', 'Text');

$purifier = new HTMLPurifier($config);

From what I gather, this means that I need to "add an attribute to the HTML Purifier definition".

So, my question is: Is there a way to do this with the .json purifier config file? Or should I try a custom plugin as described here?

I've never built a plugin, so obviously I would prefer the former. In any case, I would appreciate any pointers! Thanks in advance!

1 Answer 1


As best as I can tell, there's no way to do this through the config file. Or rather, if there is, it wouldn't be pleasant to maintain and debug.

However, Craft does provide an event trigger that gives you the opportunity to make changes to the HTMLPurifier Config when it's created.

The easiest way to take advantage of this is by watching for this event from within a custom module.

If you don't already have a custom module for your site, you can read Andrew's Welch's blog for detailed instructions on how / why you should have one: https://nystudio107.com/blog/enhancing-a-craft-cms-3-website-with-a-custom-module

Once you have a custom module (or plugin), this is an example of the code you'll need to add to it to define your own rules:

// ...

use craft\redactor\Field AS RedactorField;

// ...

class YourCustomModule extends Module
    // ...

    public function init()

        // ...

            function (Event $event) {
                if( $event->config ) {
                    if( $def = $event->config->getDefinition('HTML', true) ) {
                        // http://htmlpurifier.org/docs/enduser-customize.html#addAttribute
                        $def->addAttribute('a', 'aria-whatever', 'Text');
                        $def->addAttribute('a', 'data-whatever', 'Text');

    // ...

The above example allows the attributes aria-whatever and data-whatever on <a> elements.

Unfortunately, there's no way to allow wildcards (at least not that I can tell), so something like this won't work:

$def->addAttribute('a', 'data-*', 'Text');

Hope that helps.

  • There is extra config for htmlpurifier available at /config/htmlpurifier/Default.json. But for some reason adding HTML.AllowedAttributes and specifying data attributes there throws an error (Attribute "..." in element "..." not supported). So your solution is the only way for me. Thanks.
    – muffir
    Commented Feb 22 at 12:05

Your Answer

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

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