Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Last active October 20, 2023 15:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommcfarlin/5bd22e01487fd22df526c1a2e8687d13 to your computer and use it in GitHub Desktop.
Save tommcfarlin/5bd22e01487fd22df526c1a2e8687d13 to your computer and use it in GitHub Desktop.
[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