• Home
  • Cloud
    • General
    • SaaS
    • BPaaS
    • PaaS
    • IaaS
    • Other Internet Hosted Applications
      • WordPress
        • WooThemes Canvas
          • WooThemes Canvas CSS
  • About me
  • Why Badly Wired?
  • Contact

Badly Wired

Connecting WordPress via APIs, Plugins and other stuff - a technical notebook

You are here: Home / Code snippets / Code to delete all images from WordPress or nearly all

Code to delete all images from WordPress or nearly all

10th November 2014 by Alan 2 Comments

Fully Managed UK Hosting - Only £1+VAT till 1st Jan 2021 on Shared, Reseller and Dedicated Hosting! .... read more ....

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.

Fully Managed UK Hosting - Only £1+VAT till 1st Jan 2021 on Shared, Reseller and Dedicated Hosting! .... read more ....

The first thing was how to write code that runs using wordpress, you can use  technique simply to load wordpress

// 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

$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

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

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 )

<?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>';
     }
   }
}
?>

 

When you come to run this, it is best to run as a command line ( or via cron ) e.g.  /usr/bin/php deleteimages.php  as php on the command line won’t time out, whereas running from a web page e.g. https://example.com/deleteimages.php  will be subject to php time out limits and if you are deleting lots you will need to keep re running

 

 

 

[Next] Find out where to host WordPress [Read the full article…]

Filed Under: Code snippets, Tech Tips, Wordpress  

About Alan

I'm Alan from Fullworks Digital Ltd, where I develop WordPress Plugins and support and manage WordPress websites.

My day job consists of solving clients' WordPress issues and developing new code and solutions.

I started as a professional programmer in 1979 and had been involved with the IT of business technology in virtually every area that exist.

Badlywired.com is my personal blog and my aide memoire of the many interesting facts that I come across. As I spend a lot of time gathering parts of solutions from the internet and assembling them into my own solutions, and also just learning how to do things, this blog is primarily my 'note book' and a way of giving something back to the online community that has helped me extensively.

Comments

  1. Pascal Roget says

    14th January 2017 at 1:39 am

    Good thing badlywired.com/delmedia.php returns a 404 🙂

    Reply
    • Alan says

      24th May 2017 at 10:24 pm

      Ha Ha

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • Applications
  • Cloud
    • General
    • Google Cloud
    • IaaS
    • Other Internet Hosted Applications
      • Wordpress
        • WooThemes Canvas
        • WooThemes Canvas CSS
    • SaaS
  • Code snippets
  • Discounts
  • Genesis
  • Google Apps for Works
  • Linux
  • News
  • SEO
  • Server setup
  • Services
  • Tech Tips
  • Uncategorised
  • Useful Images
  • Useful Stuff
  • WordPress Hosting
  • WordPress Plugins

Tags

background jobs beadcrumbs bind brandings Cache canvas Centos chrome css fail2ban Find firefox Flash fraud genesis gocardless godaddy Google google maps hackers internet explorer javascript KashFlow Linus linux Magento mapquest maps microsoft mysql news nohup php plugin plugins queens diamond jubilee replace SED SEO skype Varnish Virtualmin Webmin woothemes Wordpress

 

Affiliate and Privacy Notices

This site is free to use, but hopes to cover some costs through affiliate income, some products and links are affiliates and may earn the site advertising income.

Some affiliates use Cookies to track if you purchase from them, this allows them to apportion revenue to us you will need to refer to their specific privacy notices as to how you are tracked.

This site is a participant in the Amazon EU Associates Programme, an affiliate advertising programme designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.co.uk.

  • Privacy Policy

Copyright © 2021 · Badly Wired