Skip to content

Add custom attribute on WYSIWYG content

Maylis Agniel edited this page Aug 24, 2018 · 3 revisions

functions.php

function add_text_input_classes($content) {
    $doc = new DOMDocument();

    // Load the Post/Page content as HTML
    // Source for utf-8 fix: https://stackoverflow.com/a/8218649/616095
    $doc->loadHTML('<?xml encoding="utf-8" ?>' .$content); 
    
    // Find all h2
    $titles = $doc->getElementsByTagName('h2'); 
    foreach($titles as $title){
        append_attr_to_element($title, 'class', 'yeah');
    }
    
    // Return modified content as string
    return $doc->saveHTML(); 
}

// Customize WYSIWYG output
// For WP content
// Source: https://stackoverflow.com/a/10509005/616095
add_filter('the_content', 'add_text_input_classes', 20);
// For ACF fields
// Source: https://support.advancedcustomfields.com/forums/topic/add-a-class-to-the-last-paragraph-tag-of-a-wysiwyg-field/
add_filter('acf_the_content', 'add_text_input_classes', 20);

function append_attr_to_element(&$element, $attr, $value) {
    // If the element has the specified attribute
    if($element->hasAttribute($attr)) {
        // Explode existing values
        $attrs = explode(' ', $element->getAttribute($attr)); 

        if(!in_array($value, $attrs))
            $attrs[] = $value; // Append the new value

        // Clean existing values
        $attrs = array_map('trim', array_filter($attrs)); 

        // Set cleaned attribute
        $element->setAttribute($attr, implode(' ', $attrs)); 
    }
    else
        $element->setAttribute($attr, $value); // Set attribute
}

Clone this wiki locally