Skip to content

Instantly share code, notes, and snippets.

@Soben
Last active October 3, 2019 20:29
Show Gist options
  • Select an option

  • Save Soben/02c1ff2be42861990a6754b713d9fc89 to your computer and use it in GitHub Desktop.

Select an option

Save Soben/02c1ff2be42861990a6754b713d9fc89 to your computer and use it in GitHub Desktop.
<?php
function nyo_truncate_content ( $content ) {
require_once( AMP__DIR__ . '/includes/utils/class-amp-dom-utils.php' );
$elementsRemaining = 2;
$contentDOM = \AMP_DOM_Utils::get_dom_from_content(apply_filters('the_content', $content) ); // Returns a DOMDocument
$contentDOMParsed = clone $contentDOM;
// Strip all elements from the body.
$originalBody = $contentDOM->getElementsByTagName('body')->item(0);
$parsedBody = $contentDOMParsed->getElementsByTagName('body')->item(0);
while ($parsedBody->hasChildNodes()) {
// We're starting fresh. Remove all existing elements from the processed clone
$parsedBody->removeChild($parsedBody->firstChild);
}
foreach($originalBody->childNodes as $element) {
if ($elementsRemaining < 0) { // We are out of the number of elements we want
break;
}
// Import Node into new document and append.
$importedNode = $contentDOMParsed->importNode($element, true);
$parsedBody->appendChild($importedNode);
$elementsRemaining--;
}
$content = \AMP_DOM_Utils::get_content_from_dom( $contentDOMParsed ); // Returns ONLY what's within the body tag, in string format.
return $content;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment