Family Encyclopedia >> Electronics

How to Automatically Generate Grayscale Images in WordPress

Ever wished you could automatically convert uploaded images to grayscale in WordPress? As a seasoned WordPress developer, I've streamlined this process using built-in PHP image tools and core functions. This technique is ideal for post thumbnails, sliders, galleries, or any creative element.

How to Automatically Generate Grayscale Images in WordPress

Start by opening your theme's functions.php file and adding this code to register a custom image size:

add_action( 'after_setup_theme', 'themename_bw_size' );
function themename_bw_size() {
    add_image_size( 'themename-bw-image', 100, 100, true );
}

This registers a new 100x100 pixel image size with hard cropping. Adjust dimensions as needed for your design.

Next, add this filter to apply the grayscale effect during image processing:

add_filter( 'wp_generate_attachment_metadata', 'themename_bw_filter' );
function themename_bw_filter( $meta ) {
    $upload_dir = wp_upload_dir();
    $path = trailingslashit( $upload_dir['path'] ) . $meta['sizes']['themename-bw-image']['file'];

    if ( ! file_exists( $path ) ) {
        return $meta;
    }

    list( $w, $h, $type ) = getimagesize( $path );

    $src = null;
    switch ( $type ) {
        case IMAGETYPE_JPEG:
            $src = imagecreatefromjpeg( $path );
            break;
        case IMAGETYPE_PNG:
            $src = imagecreatefrompng( $path );
            break;
        case IMAGETYPE_GIF:
            $src = imagecreatefromgif( $path );
            break;
    }

    if ( $src ) {
        imagefilter( $src, IMG_FILTER_GRAYSCALE );
        switch ( $type ) {
            case IMAGETYPE_JPEG:
                imagejpeg( $src, $path, 90 );
                break;
            case IMAGETYPE_PNG:
                imagepng( $src, $path );
                break;
            case IMAGETYPE_GIF:
                imagegif( $src, $path );
                break;
        }
        imagedestroy( $src );
    }

    return $meta;
}

This code generates the custom size, then converts it to grayscale using PHP's GD library, saving the processed version. It supports GIF, PNG, and JPEG formats.

For post thumbnails, display it in your theme templates like this:

the_post_thumbnail( 'themename-bw-image' );

Or for a specific attachment ID:

wp_get_attachment_image( $attachment_id, 'themename-bw-image' );

Important: Replace 'themename' with your actual theme folder name to avoid conflicts.

Full credit for this clever technique goes to Otto, a respected WordPress core contributor.