Last Updated: February 25, 2016
·
3.793K
· lightandsounds

Automatically convert uploaded images to grayscale in Wordpress

add_filter('wp_generate_attachment_metadata','rb_bw_filter');

function rb_bw_filter($meta) {

    $path = wp_upload_dir(); // get upload directory
    $file = $path['basedir'].'/'.$meta['file']; // Get full size image

    $files[] = $file; // Set up an array of image size urls

    foreach ($meta['sizes'] as $size) {
        $files[] = $path['path'].'/'.$size['file'];
    }

    foreach ($files as $file) { // iterate through each image size

        // Convert image to grayscale credit to http://ottopress.com/2011/customizing-wordpress-images/

        list($orig_w, $orig_h, $orig_type) = @getimagesize($file);
        $image = wp_load_image($file);
        imagefilter($image, IMG_FILTER_GRAYSCALE);
        switch ($orig_type) {
            case IMAGETYPE_GIF:
                imagegif( $image, $file );
                break;
            case IMAGETYPE_PNG:
                imagepng( $image, $file );
                break;
            case IMAGETYPE_JPEG:
                imagejpeg( $image, $file );
                break;
        }
    }
    return $meta;
}