Created
June 14, 2015 05:53
-
-
Save hattmarris/0ce525070b5850266f0e to your computer and use it in GitHub Desktop.
Strip plain text (leave HTML tags) from all posts in WordPress loop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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