Skip to content

Instantly share code, notes, and snippets.

@hattmarris
Created June 14, 2015 05:53
Show Gist options
  • Save hattmarris/0ce525070b5850266f0e to your computer and use it in GitHub Desktop.
Save hattmarris/0ce525070b5850266f0e to your computer and use it in GitHub Desktop.
Strip plain text (leave HTML tags) from all posts in WordPress loop
<?php
$args = array(
'post_type' => 'post' // just query for all posts
);
$query = new WP_Query($args); // create new WP_Query object
if($query->have_posts()) {
while($query->have_posts()) {
$query->the_post();
$content = get_the_content();
$dom = new DOMDocument; // create new PHP DOM object
$dom->loadHTML($content, HTML_PARSE_NOIMPLIED); // load the $content into the DOM object, HTML_PARSE_NOIMPLIED prevents auto adding <html> and <body> tags
$xpath = new DOMXpath($dom); // create new Xpath object with DOM
foreach ($xpath->evaluate('//text()') as $node) {
$node->parentNode->removeChild($node); // loops through finds plain text and removes
}
$new_content = $dom->saveHtml($dom->documentElement); // save your new DOM with plain text removed
// Arguments for wp_update_post
$new_post = array(
'ID' => $post->ID, // current post ID in the WP loop
'post_content' => $new_content
);
// Update the post into the database
wp_update_post( $new_post );
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment