Skip to content

Instantly share code, notes, and snippets.

@kierzniak
Last active January 2, 2018 08:06
Show Gist options
  • Save kierzniak/6c89f900104dd0233ae593ae81941f01 to your computer and use it in GitHub Desktop.
Save kierzniak/6c89f900104dd0233ae593ae81941f01 to your computer and use it in GitHub Desktop.
Remove unwanted content from posts
<?php
/**
* Remove unwanted content from posts
*
* When your site get hacked you can have some unwanted content in database like
* links or script tags. This script will mass update all your posts to remove
* this kind of content. Take a look to $regex variable and remove or add pattern
* to fit your needs. To test regex you can use tool like https://regex101.com/
*
* Script will not trigger automatically you must add "update" parameter to your
* site url e.g. http://example.org?update=1
*
* If you have many posts disable creating revision posts by adding
* WP_POST_REVISIONS constant to wp-config.php. It will speed up script
* and reduce the demand for memory usage. define( 'WP_POST_REVISIONS', false );
*
* For 1000 posts script executes about 30s and use 45mb memory
* on 1 CPU and 512mb machine.
*/
function motivast_remove_unwanted_content() {
$update = filter_input(INPUT_GET, 'update', FILTER_SANITIZE_NUMBER_INT);
if( $update === '1' ) {
// Get all posts
$query = new WP_Query(array(
'post_type' => 'post',
'posts_per_page' => -1,
'order' => 'ASC',
));
$posts = $query->get_posts();
foreach ($posts as $post) {
// Get content
$content = $post->post_content;
// Regex and replacement
$regex = array(
'/^\<script\>.+\<\/script\>$/mg', // Any script tag
'/^\<a.+>.+\<\/a\>$/mg', // Any link in the post
'/^\<a.*href=\"http:\/\/example\.org\".*\>.+\<\/a\>$/mg', // Link with http://example.org in the href
);
$replacement = '';
// Replace content
$new_content = preg_replace($regex, $replacement, $content);
// Prepare arguments
$args = array(
'ID' => $post->ID,
'post_content' => $new_content,
);
// Update post
wp_update_post( $args );
}
}
}
add_action('init', 'motivast_remove_unwanted_content');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment