Recently one image got entangled by a copyright claim from Copyright Agent on the website FrågaDietisten.se, an author had by mistake and unknowingly uploaded a photo belonging to TT and now had to pay a hefty fee. To avoid any further expensive mistakes, and in all a bit of a haste, I decided to write a little script to remove all images. I am sure there are more elegant ways to do this but I am pasting it here in case someone else finds this useful;
<?php
header(’Content-Type: text/html; charset=utf-8’);
// Add your database information here, if you don’t know it just check your wp-config.php
$databas = ”;
$user = ”;
$password = ”;
$host = ’localhost’;
$connect = mysqli_connect($host,$user,$password);
$connect->select_db($databas);
$connect->query(”SET NAMES ’utf8’ ”) or die($connect->error());
$connect->query(”SET CHARACTER SET utf8”) or die($connect->error());
function NyTid($var) {
$date = date_create($var);
$date->modify(’-1 minute’);
return $date->format(’Y-m-d H:i:s’);
}
$sql =”SELECT * FROM `wp_posts` WHERE `post_type`=’post’ AND `post_status`=’publish'”;
$result = $connect->query($sql);
while ($array = $result->fetch_array(MYSQLI_BOTH)){
$id = $array[’ID’];
$post_content = addslashes(preg_replace(”/<img[^>]+\>/i”, ” ”, $array[’post_content’]));
$post_content_original = addslashes($array[’post_content’]);
// Remove images from posts in database.
$sql_ett = ”UPDATE wp_posts SET `post_content` = ’$post_content’ WHERE ID = $id”;
$result_ett = $connect->query($sql_ett);
// Remove featured images.
$sql_rensa_a =”DELETE FROM wp_postmeta WHERE meta_key =’_wp_attached_file'”;
$sql_rensa_b =”DELETE FROM wp_postmeta WHERE meta_key =’_wp_attachment_metadata'”;
$result_a = $connect->query($sql_rensa_a);
$result_b = $connect->query($sql_rensa_b);
// Create a revision/draft as a backup.
// NOTE: If there are no revisions then the post will not be saved in its original state. This SQL selects the oldest revision.
$sql_backup_a =”SELECT * FROM `wp_posts` WHERE post_parent =$id AND post_type=’revision’ ORDER BY post_date ASC LIMIT 1″;
$result_backup_a = $connect->query($sql_backup_a);
$array_backup_a = $result_backup_a->fetch_array(MYSQLI_BOTH);
$backup_id = $array_backup_a[’ID’];
$sql_backup_b =”UPDATE wp_posts SET `post_content` = ’$post_content_original’ WHERE ID = $backup_id”;
$connect->query($sql_backup_b);
echo ”.”;
}
?>
After also removing all images in the image library it might be a good idea to disable hotlinking in case some image is still forgotten in your uploads folder, easiest way to do this I think is by ModRewrite. Simply upload a .htaccess file in your uploads folder and replace with your domain and choose https/http depending on your site settings:
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^https://(www\.)fragadietisten.se/.*$ [NC]
RewriteRule \.(gif|jpg|jpeg|mp3|png|pdf|zip)$ – [F]