How to access the html content of the page?
-
I am trying to replace the img tags of the dom before it is printed, for that I need to access the html of the page but the_content filter does not work for me.
This is my last code I tried but it doesn’t do anything at all:
Update: I tried the get image_tag filter supposedly suitable for this task but it doesn’t change anything anyway, it doesn’t work
function image_tag($html, $id, $alt, $title) { return preg_replace(array( '/'.str_replace('//','//',get_bloginfo('url')).'/i', '/s+width="d+"/i', '/s+height="d+"/i', '/alt=""/i' ), array( '', '', '', 'alt="' . $title . '"' ), $html); } add_filter('get_image_tag', 'image_tag', 0, 4);
function change_html($the_content) { $post = new DOMDocument(); $post->loadHTML($the_content); $imgs = $post->getElementsByTagName('img'); foreach( $imgs as $img ) { if( $img->hasAttribute('data-src') ) continue; if( $img->parentNode->tagName == 'noscript' ) continue; $clone = $img->cloneNode(); $src = $img->getAttribute('src'); $img->removeAttribute('src'); $img->setAttribute('data-src', $src); $width = $img->getAttribute('width'); $img->removeAttribute('width'); $img->setAttribute('data-width', $width); $height = $img->getAttribute('height'); $img->removeAttribute('height'); $img->setAttribute('data-height', $height); $imgClass = $img->getAttribute('class'); $img->setAttribute('class', $imgClass . ' fs-img'); $no_script = $post->createElement('noscript'); $no_script->appendChild($clone); $img->parentNode->insertBefore($no_script, $img); }; return $post->saveHTML(); } add_filter('the_content', 'change_html');
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
- The topic ‘How to access the html content of the page?’ is closed to new replies.