Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin tommcfarlin/00-acme-class.php Secret
Created Feb 13, 2018

Embed
What would you like to do?
[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
You can’t perform that action at this time.