Is it adivsable to use DOMDocument on Wordpress content?

160 views Asked by At

I'd like to tinker with the content Worpress generates before it gets displayed.

A lot of examples I saw so far use regex to change the content even though it is bad practise and not advisable to parse html with regex.

My idea now is to use DOMDocument to parse and change the HTML. Is that a good idea or can this break the integrity of the content in any way?

Here is some example Wordpress content filter I created (it scales the images down half the size for retina displays):

function fancyContentParser( $content ) {

    $dom = new DOMDocument();
    $dom->loadHTML($content);

    $images = $dom->getElementsByTagName('img');

    foreach ($images as $image) {

        $width = $image->getAttribute('width')/2;
        $height = $image->getAttribute('height')/2;
        $style = 'width: '.$width.'px; height: '.$height.'px';

        $image->setAttribute('style', $style); 

    }

    return $dom->saveHTML();

}

add_filter( 'the_content', 'fancyContentParser' );
1

There are 1 answers

2
rnevius On

The answers to this question are probably going to be primarily opinion-based...but I don't see anything wrong with it. However, why wouldn't you just change the width and height attributes, rather than overriding them with style?

foreach ($images as $image) {

    $image->setAttribute( 'width', $image->getAttribute('width')/2 );
    $image->setAttribute( 'height', $image->getAttribute('width')/2 );

}

Additionally, you can likely accomplish this without DOMDocument...and just use CSS (which is what you're proposing in your question by using a style attribute anyways). You can use the transform property:

img {
    -webkit-transform: scale(0.5);
            transform: scale(0.5);
}