Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin tommcfarlin/00-use-dom-document.php Secret
Last active Jun 4, 2019

Embed
What would you like to do?
[PHP] Manipulate the DOM Using PHP
<?php
use DOMDocument;
<?php
add_filter('the_content', __NAMESPACE__ . '\\updateParagraphElements');
<?php
function updateParagraphElements($content)
{
/* If we're not on a single page or it's not the main query,
* we won't do anything.
*/
if (!is_single() || !is_main_query()) {
return $content;
}
// Make sure there is content to parse (and properly encode the HTML entities).
$domDocument = new DOMDocument();
$domContent = $domDocument->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES'));
if (false === $domContent) {
return $content;
}
$paragraphs = $domDocument->getElementsByTagName('p');
if (0 === count($paragraphs)) {
return $content;
}
// More to come...
}
<?php
namespace Acme;
use DOMDocument;
add_filter('the_content', __NAMESPACE__ . '\\updateParagraphElements');
/**
* Updates the content by locating all of the `p` elements in the content,
* then adds a class attribute of the post ID to them.
*
* The gist of the work is done in this function.
*
* @param string $content the post content
*
* @return string the updated post content with the aforemented markup.
*/
function updateParagraphElements($content)
{
/* If we're not on a single page or it's not the main query,
* we won't do anything.
*/
if (!is_single() || !is_main_query()) {
return $content;
}
// Make sure there is content to parse (and properly encode the HTML entities).
$domDocument = new DOMDocument();
$domContent = $domDocument->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES'));
if (false === $domContent) {
return $content;
}
$paragraphs = $domDocument->getElementsByTagName('p');
if (0 === count($paragraphs)) {
return $content;
}
// If so, iterate through the elements and add the post ID as a custom attribute.
$updatedContent = '';
foreach ($paragraphs as $paragraph) {
$paragraph->setAttribute('data-id', get_the_ID());
}
return wp_kses_post($domDocument->saveHTML());
}
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.