How to Grayscale Images in WordPress

0
0



Did you ever wonder if there was a way to automatically grayscale images in WordPress when you upload them? Well the wondering time is over. In this article, we will show you how you can use some simple PHP image manipulation tools and WordPress functions to automatically grayscale images upon upload. You can use grayscale images for hover, sliders, gallery, or anything else you like.

First thing you need to do is open your theme’s functions.php file and add the following code:

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

The code above simply adds an additional image size for the uploader. The size is set to 100 x 100px with hard cropping. You may change the dimensions to fit your needs. Once you have done that, you need to add the following code:

add_filter(‘wp_generate_attachment_metadata’,’themename_bw_filter’);
function themename_bw_filter($meta) {
$file = wp_upload_dir();
$file = trailingslashit($file[‘path’]).$meta[‘sizes’][‘themename-bw-image’][‘file’];
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;
}

The code above pretty much tells the uploader to create an extra size of the image you uploaded. Crop it to the size you have specified in the previous step. Then apply the image filter: Grayscale.

If you were doing this for your post thumbnails, then you can display it like this in your theme:

< ?php the_post_thumbnail( 'themename-bw-image' ); ?>

If you want to do this for a specific attachment, then you can use wp_get_attachment_image function.
Note: You should change themename to your theme’s name.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>