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

Do you find yourself constantly switching between WordPress and a photo editor just to grayscale images before uploading them? It’s a tedious and inefficient process to edit each photo individually beforehand.

Luckily, through years of WordPress experimentation, we’ve discovered a simple way to automatically grayscale images during upload, saving you valuable time.

In this article, we’ll show you how to grayscale images in WordPress while uploading them to your site, step-by-step.

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.

Grayscaling 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 the best code snippets plugin that helps you run code snippets without the need to manually edit your theme’s function.php file. That way, you don’t have to worry about breaking your site.

WPCode

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.

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.

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 code snippet in WPCode

Next, you need to select ‘PHP Snippet’ as the code type from the options that appear.

Select PHP Snippet as the code type

Now, on the Create Custom Snippet page, go ahead and enter a name for your snippet. This can be anything to help you remember what the code is for.

Then, paste the above code in the ‘Code Preview’ area.

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 from ‘Inactive’ 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 add dark mode to your WordPress site 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

17 CommentsLeave a Reply

  1. Tomas Kapler

    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

  2. rok

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

  3. Kim

    Will this change all pictures in word press to grayscale or only newly updates ones?

  4. Tomaž Zaman

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

  5. endul

    how to change, result filter image to specific folder/directory

    • mklemme

      @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:

    • Mike Logan

      Excellent idea, almost 10 years later this is still handy.

  6. geertvdheide

    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

      @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!

  7. frankiegershwin

    @Otto42 Thanks for offering. I will.

  8. frankiegershwin

    @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

  9. Otto42

    @frankiegershwin Lemme know if you need help. I added a way to do sepia tones too in my comments on the original post: http://t.co/avDNNEX

  10. rodhk

    @rodriguezhernan vaya idiotez de truco…. madremua tocar el codigo para eso

  11. wpbeginner

    @Otto Thanks for the comment Otto. Updated the post as well :)

  12. Otto

    Note that people should change “themename” to be the name of their theme instead.

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.