The other day I had a bit of a nightmare with a plugin that looped and created multiple images, in fact thousands of them.
I got bored with trying to delete them manually so wrote some code quickly.
The first thing was how to write code that runs using wordpress, you can use technique simply to load wordpress
1 2 |
// Include the wp-load'er include('wp-load.php'); |
once loaded you can then use all the WordPress functions
First I want to get all the attachments, these are just post types so it is matter of calling get_posts
1 2 3 4 5 6 7 |
$args= array( 'post_type' => 'attachment', // obvious 'posts_per_page' => -1 // get them all ); // get all attachments post ids $posts = get_posts( $args ); |
Then a loop getting the image data
1 2 3 4 5 |
foreach ($posts as $post_id) { // get an array of image data $image_attributes = wp_get_attachment_image_src( $post_id->ID ); // do stuff } |
In this case I wanted to only delete images that had a certain string so I can do this with strpos to identify the right image by string and wp_delete_attachment to delete it. Of course you could use preg_match for complex matching http://php.net/manual/en/function.preg-match.php
1 2 3 4 5 6 7 8 |
if (strpos($image_attributes[0], 'mystring') !== false){ echo 'Image Found : '.$image_attributes[0]; if (false === wp_delete_attachment( wp_delete_attachment( $post_id->ID, true ) ) ) { echo ' and delete failed!<br>'; } else { echo ' and delete succeeded!<br>'; } } |
Add it all together and you get something like this. Be careful, use at your own risk, and always backup your database first. (I’d recommend commenting out the delete first too, to make sure )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?php /* create this code in a file in the main wordpress directory e.g. delmedia.php and access it via mydomain.com/delmedia.php */ // Include the wp-load'er include('wp-load.php'); $args= array( 'post_type' => 'attachment', // obvious 'posts_per_page' => -1 // get them all ); // get all attachments post ids $posts = get_posts( $args ); foreach ($posts as $post_id) { // get an array of image data $image_attributes = wp_get_attachment_image_src( $post_id->ID ); if (strpos($image_attributes[0], 'mystring') !== FALSE){ echo 'Image Found : '.$image_attributes[0]; if (false === wp_delete_attachment( wp_delete_attachment( $post_id->ID, true ) ) ) { echo ' and delete failed!<br>'; } else { echo ' and delete succeeded!<br>'; } } } ?> |
Good thing badlywired.com/delmedia.php returns a 404 🙂
Ha Ha