Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
WPB Cup
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

How to Grayscale Images in WordPress

Editorial Note: We earn a commission from partner links on WPBeginner. Commissions do not affect our editors' opinions or evaluations. Learn more about Editorial Process.

Are you wondering if there was a way to automatically grayscale images in WordPress when you upload them?

Usually, you need a photo editing tool to change your images to grayscale. However, this can be time-consuming as you’ll need to edit each individual image before uploading it to your website.

In this article, we will show you how to grayscale images in WordPress while uploading to your site.

Greyscale Images in WordPress

When Should You Use Grayscale Images in WordPress?

Grayscale images only contain information about the amount of light in the picture. Image colors show different shades of grey, varying between black and white.

Under certain situations, using grayscale images can be beneficial for your WordPress website. For instance, you can use it to improve the readability of the objects shown in the image.

On the other hand, grayscale images are commonly used for image processing because of their small size. It allows developers to run complex operations in a shorter time.

That said, let’s see how you can turn your images to grayscale in WordPress when you upload them.

Graysacling Images on Upload in WordPress

When it comes to adding images in WordPress, you would have to edit them before uploading using a photo editing software like Photoshop and convert colored pictures to grayscale.

If you have hundreds or thousands of images to upload, then it can take a lot of time to edit each picture manually.

However, you can automatically turn them into grayscale images upon upload. To start, all you have to do is add the following code to your theme’s functions.php file:

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;
}

A simple way of adding code to theme files is by using the WPCode plugin for WordPress. It’s a free plugin that helps you run code snippets without the need to manually edit your theme’s function.php file.

Note: The free version of WPCode offers everything you need to easily add custom code in WordPress. For more advanced features like a private cloud snippet library, scheduled snippets, conversion pixels, and more, you can upgrade to WPCode Pro.

First, you’ll need to download and install the free WPCode plugin on your site. If you need help, then please follow our guide on how to install a WordPress plugin.

Upon activation, you can head over to Code Snippets » + Add New from your WordPress dashboard.

Then, navigate to the ‘Add Your Custom Code (New Snippet)’ option and click on the ‘Use snippet’ button.

Add a new custom snippet in WPCode

Next, go ahead and enter a name for your snippet and paste the above code in the ‘Code Preview’ area.

You also need to select ‘PHP Snippet’ as the code type from the dropdown list on the right.

Add code snippet for grayscale images

After entering the code, you can scroll down to the ‘Insertion’ section.

Here, you can leave the ‘Auto Insert’ option selected. This will automatically insert and execute the code for you.

Insertion methods for snippets in WPCode

Lastly, go back to the top of the screen and toggle the switch to ‘Active’ and click the ‘Save Snippet’ button.

Save and activate your custom code snippet

Next, you can test the code by editing or adding a new page. When you’re in the WordPress editor, go ahead click the ‘+’ button and add an Image block.

You can now upload any image on your WordPress blog and it will automatically convert into a grayscale image.

Convert images to grayscale on upload

We hope this article helped you learn how to grayscale images in WordPress. You can also check out our guide on how to choose the best blogging platform and our expert picks of the best web design software.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Disclosure: Our content is reader-supported. This means if you click on some of our links, then we may earn a commission. See how WPBeginner is funded, why it matters, and how you can support us. Here's our editorial process.

Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

The Ultimate WordPress Toolkit

Get FREE access to our toolkit - a collection of WordPress related products and resources that every professional should have!

Reader Interactions

18 CommentsLeave a Reply

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Tomas Kapler says

    Great tip, i would just like to mention, that for many usages it might be better to simply do this via CSS filter, e.g.
    img.bw {
    filter: grayscale(1);
    }
    you can even e.g. show b/w by default and color on hover, or you can do animation from greyscale to full color and back, e.g.
    img.bw {
    filter: grayscale(0);
    }

    img.bw.grey {
    filter: grayscale(1);
    transition-property: filter;
    transition-duration: 1s;
    }

    i also do not think, that wp_generate_attachment_metadata filter is the proper one, that should be used because of its calling in meta creation not only image creation and making second image manipulation, but the proper solution would be much longer, so i understand why it is done this way

  3. rok says

    It works nice but when uploading, WP 4.3 throws error in media library.
    i think have applied all fixes written in comments, but still error.

    my code looks like this:

    add_filter(‘wp_generate_attachment_metadata’,’themename_bw_filter’);
    function themename_bw_filter($meta) {
    $time = substr( $meta[‘file’], 0, 7); // <- get the correct time of the upload
    $file = wp_upload_dir( $time ); // <- locates the correct upload directory
    $file = trailingslashit($file[‘path’]).$meta['sizes']['slide-pic']['file'];
    if( $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;
    }

  4. Tomaž Zaman says

    I know I’m a bit late to the discussion, but I just had the same problem with an error (that others report):

    imagefilter() expects parameter 1 to be resource, string given

    This happens when you try to upload image through media modal while editing a post, older than the current month which apparently confuses WordPress which directory the original image is in and which directory it should save the grayscaled image in.

    This is the solution:


    <?php
    add_filter('wp_generate_attachment_metadata','themename_bw_filter');
    function themename_bw_filter($meta) {
    $time = substr( $meta['file'], 0, 7); // <- get the correct time of the upload
    $file = wp_upload_dir( $time ); // <- locates the correct upload directory
    $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;
    }

    • mklemme says

      @geertvdheide

      If you wanted to add multiple size support, try what I use:

      if ( function_exists( ‘add_theme_support’ ) ){

      add_theme_support( ‘post-thumbnails’ );

      set_post_thumbnail_size( 50, 50, true );

      add_image_size( ‘medium-thumb’, 660, ”, true );

      add_image_size( ‘large-thumb’, 960, ”, true );

      add_image_size( ‘small-thumb’, 100, ”, true );

      }

      (The height is not defined, only the width.)

      you would have to add the different names to make the function apply to them all:

      [‘medium-thumb’ , ‘large-thumb’ , ‘small-thumb’] in the filter code.

      Calling the thumbnail in your theme is the same listed in the article:

  5. geertvdheide says

    Thanks for sharing this code! Except I’m running into a weird issue when trying to implement it. It’s related to the uploaded image’s size (pixel size, meaning its dimensions). Copied the code literally to my theme’s functions.php, and it works a charm with images larger than the size specified in the add_image_size call. But when using an image smaller than or equal to the size specified, the uploader in WordPress gives me errors and doesn’t process the image size (either from the media section of the admin environment, or from a specific post or page). The error:

    Warning: imagefilter() expects parameter 1 to be resource, string given.

    Ssome other stuff in the error as well, but this seems to be the main cause. The image data given to the imagefilter function must not be valid or doesn’t exist?

    Any idea what’s causing this? The only real difference between my situation and a clean install is that I’ve also added a few other add_image_size calls for other purposes in my site. I’m also adding the same size twice (one black/white, one regular), but that doesn’t seem to be a problem with the larger images.

    • Ed Nailor says

      @GEERTVDHEIDE

      and for others that need this:

      When the script is converting the image to greyscale and the file uploaded does not fit the file size, this causes the script to break. To prevent this, simply add a quick if() conditional to make sure you have the $file.

      $file = trailingslashit($file[‘path’]).$meta[‘sizes’][‘themename-bw-image’][‘file’];
      if( $file ) {
      list($orig_w, $orig_h, $orig_type) = @getimagesize($file);
      ——– remainder of code until ——–
      return $meta;
      }

      This will check to make sure the file size you have requested exists before it tries to convert it.

      Hope that helps!

  6. frankiegershwin says

    @Otto42 thank you! I had a bit of a hard time, actually and had to undoe it :( will pick it up tomorrow. It’s a good way to mix it up onsite

Leave A Reply

Thanks for choosing to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published. Please Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WPBeginner Assistant
How can I help you?

By chatting, you consent to this chat being stored according to our privacy policy and your email will be added to receive weekly WordPress tutorials from WPBeginner.