user1359872
user1359872

Reputation:

Delete Images after Post

My client is using WordPress for real estate listings. Currently, she is not cleaning up her listings and running out of disk space. What WordPress configuration is possible to have WordPress delete the pictures associated with a page / post that was deleted. As it stands now, I would have to note the pictures and then go into the media library.

Upvotes: 1

Views: 1806

Answers (2)

Obmerk Kronen
Obmerk Kronen

Reputation: 15949

This should do the trick ...

 function o99_delete_post_children($post_id) {
        global $wpdb;

        $child_atts = $wpdb->get_col("SELECT ID FROM {$wpdb->posts} WHERE post_parent = $post_id AND post_type = 'attachment'");

        foreach ( $child_atts as $id )
            wp_delete_attachment($id);
    }
    add_action('before_delete_post', ' o99_delete_post_children');
    add_action('trash_post', 'o99_delete_post_children')

Disclaimer : Never tried this , so please TEST on a non-production environment first - or use at your own risk...

EDIT I: thanks to @Dale Sattler for comment

EDIT II: added add_action('trash_post', 'o99_delete_post_children'); to support also "move to trash" action in admin list post (and not one by one delete)

Upvotes: 1

Jon Lachonis
Jon Lachonis

Reputation: 931

You might put this in a stand alone file as well to 'clean up' after posts that have already been deleted

<?php 
/* Short and sweet */
define('WP_USE_THEMES', false);
require('./wp-blog-header.php');

$unattachedmediaargs = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => 0
); 
$unattachedmedia = get_posts($unattachedmediaargs);
if ($unattachedmedia) {
foreach ($unattachedmedia as $unattached) {
    wp_delete_attachment( $unattached->ID, true );
            }
}
?>

Upvotes: 1

Related Questions