Ever wondered if there was a way to automatically scale grayscale images in WordPress when you upload them? Well, the time of wonders is over. In this article, we will show you how you can use some simple PHP image manipulation tools and WordPress functions to automatically scale grayscale images. You can use grayscale images for scrolling, slider, gallery or anything else you want.
The 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 to the uploader. The size is set to 100 x 100 px with hard clipping. You can change the dimensions to suit your needs. Once you've 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 ['tamaños'] ['themename-bw-image'] ['file']; list ($ orig_w, $ orig_h, $ orig_type) = @getimagesize ($ archivo); $ image = wp_load_image ($ archivo); filtro de imagen ($ imagen, IMG_FILTER_GRAYSCALE); switch ($ orig_type) case IMAGETYPE_GIF: imagegif ($ image, $ file); descanso; caso IMAGETYPE_PNG: imagepng ($ imagen, $ archivo); descanso; caso IMAGETYPE_JPEG: imagejpeg ($ image, $ file); descanso; devolver $ meta;
The code above practically tells the uploader to create an additional size of the image you uploaded. Crop it to the size you specified in the previous step. Then apply the image filter:Grayscale.
If you were doing this for your post thumbnails, you can display it like this in your theme:
If you want to do this for a specific attachment then you can use the wp_get_attachment_image function.
Note:You must change the theme name to the name of your theme.
All credits for this awesome trick go to Otto.