Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I would like to be able to refresh the thumbnail cache programmatically, not sure where to hook it, but at present any design changes mean re-uploading loads of images!

share|improve this question

1 Answer 1

up vote 3 down vote accepted

You may want to look at the plugin Regenerate Thumbnails by Viper007Bond.

Basically, this is how to do it:

function regenerateThumbnails() {

    $images = $wpdb->get_results( "SELECT ID FROM $wpdb->posts WHERE post_type = 'attachment' AND post_mime_type LIKE 'image/%'" );

    foreach ( $images as $image ) {
        $id = $image->ID;
        $fullsizepath = get_attached_file( $id );

        if ( false === $fullsizepath || !file_exists($fullsizepath) )
            return;

        if ( wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $fullsizepath ) ) )
            return true;
        else
            return false;
    }
}

Note: This function is not very scalable. It will loop through all the images and regenerate thumbnails one by one, which may consume a large amount of memory. So, you may want to enhance it.

share|improve this answer
    
how might we scale it? –  Mild Fuzz Oct 14 '10 at 9:35
    
@MildFuzz: The plugin now does this in an Ajax loop, so only one image is resized per request. You just leave the browser window open while it processes each image in sequence. If you do it in one request (as the plugin used to do), you run into memory and time limits. –  Jan Fabry Oct 14 '10 at 9:42
    
what would be good is if we could write a function that could hook into the loading of the attachment, and if the right one is not present, create it. –  Mild Fuzz Oct 14 '10 at 9:44
    
@Mild Fuzz: By "loading of the attachment", do you mean when the file is requested by the browser? If so, you'd end up putting a significant performance drain on the server because currently Apache serves images, WordPress never handles them. You could try hook the 404 template and try to figure out what to generate from there but there might but unexpected incompatibilities. Wish I had time to fiddle with it but sadly I don't right now. Maybe you could tell us a bit more about your situation and use-case? Why is the standard approach not working for you? –  MikeSchinkel Oct 14 '10 at 11:16
    
@*Mild Fuzz* - You could also run code similar to the code @sorich87 provided on a pseudo-cron task: bit.ly/wp-pseudo-cron –  MikeSchinkel Oct 14 '10 at 11:19

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.