How to Grayscale Images in WordPress




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' ); ?>




Related Post


Latest Post


Recent Posts Widget

Make sure to never miss a thing...

Get the latest news from the creative industry along with other creative goodies, conveniently delivered to social media.