Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Created February 13, 2018 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommcfarlin/44178197b6878eb43e369cf6e5de09fc to your computer and use it in GitHub Desktop.
Save tommcfarlin/44178197b6878eb43e369cf6e5de09fc to your computer and use it in GitHub Desktop.
[WordPress] Modify Image Containers on the Server-Side with WordPress
<?php
namespace Acme;
use DOMDocument;
class AcmeContentSubscriber
{
// ...
}
<?php
public function contentSubscriber()
{
add_action( 'the_content', [$this, 'addImageAttributes']);
}
<?php
public function addImageAttributes($content)
{
$content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
$document = new DOMDocument();
libxml_use_internal_errors(true);
$document->loadHTML(utf8_decode($content));
// ...
}
<?php
public function addImageAttributes($content)
{
$content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
$document = new DOMDocument();
libxml_use_internal_errors(true);
$document->loadHTML(utf8_decode($content));
$images = $document->getElementsByTagName('img');
foreach ($images as $image) {
$image->setAttribute('class', 'acme-iamge');
if ($image->nextSibling->tagName !== 'p') {
$this->wrapImage($document, $image);
}
}
// ...
}
<?php
public function addImageAttributes($content)
{
$content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
$document = new DOMDocument();
libxml_use_internal_errors(true);
$document->loadHTML(utf8_decode($content));
$images = $document->getElementsByTagName('img');
foreach ($images as $image) {
$image->setAttribute('class', 'acme-image');
if ($image->nextSibling->tagName !== 'p') {
$this->wrapImage($document, $image);
}
}
return $document->saveHTML();
}
<?php
/**
* This function is used to wrap individual images in a paragraph element.
*
* @param $document The DOM Document which is to be rendered.
* @param $image The image to wrap with the new paragraph element.
*/
private function wrapImage($document, $image)
{
if (null === $image) {
return;
}
$wrapper = $document->createElement('p');
$wrapper->setAttribute('class', 'acme-image');
$image->parentNode->replaceChild($wrapper, $image);
if (null !== $image) {
$wrapper->appendChild($image);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment