10 Code Snippets to Use Images More Effectively in WordPress

You know how important images are in the world of online marketing.

I don’t need to tell you that 65% of the people who visit your site are visual learners, or that infographics are a tried-and-tested means of producing viral content. And you’re not in the least bit surprised that blog posts with images receive 94% more views than those without.

So rather than going down that road, let’s instead explore the ways you can leverage WordPress to get the most out of your images. Below you will find 10 code snippets that will enable you to use images more effectively in WordPress. And I don’t need to tell you that’s a good thing, right?

(Unless otherwise stated, all code snippets should be inserted into your functions.php file.)

1. Remove Automatic JPEG Compression

Ensuring that your images are as small (and therefore quick to load) as practically possible is vital, which is why I so heartily recommend the WP Smush.it and TinyPNG for WordPress plugins, which compress JPEGs and PNGs so effectively that you are highly unlikely to notice the difference.

If you have those plugins installed and you’re compressing your images as you see fit yourself, you almost certainly don’t need WordPress’ built-in JPEG compression capabilities, which by default compress the web’s favorite image file type to 90% of its original quality. You can effectively turn off this function by using the following code:

add_filter( 'jpeg_quality', 'smashing_jpeg_quality' );
function smashing_jpeg_quality() {
   return 100;
}

Source: Powerful WordPress Tips And Tricks (Smashing Magazine)

2. Add a Favicon

I never cease to be amazed at how many websites don’t have a custom favicon. It’s not the biggest deal in the world, but at the same time it’s a task so easily completed that every website worth its salt should have one.

You can create a favicon from scratch or create from your logo using a web app such as favicon.cc. Once you’ve done that, upload your shiny new favicon to your theme’s root folder (i.e. /wp-content/your-theme-name/) and enable its display using the following code:

add_action( 'wp_head', 'ilc_favicon');
function ilc_favicon(){
  echo "<link rel='shortcut icon' href='" . get_stylesheet_directory_uri() . "http://media.mediatemple.netdna-cdn.com/favicon.ico' />" . "n";
}

Source: 10 Tips To Optimize Your WordPress Theme (Smashing Magazine)

3. Display Your Favicon as the Gravatar

If you don’t have the time or the inclination to create a custom favicon, a quick and easy alternative is to use your pre-existing Gravatar (hint: you’ll want to get yourself one of these if you don’t already).

The Gravatar attached to the email address listed in your WordPress profile will be used as your favicon; just enter the following code into functions.php and WordPress will do the rest!

function gravatar_favicon() {
	$GetTheHash = md5(strtolower(trim(get_bloginfo('admin_email'))));
	return 'http://www.gravatar.com/avatar/' . $GetTheHash . '?s=16';
}
function favicon() {
	echo '<link rel="Shortcut Icon" type="image/x-icon" href="'.gravatar_favicon().'" />';
}
add_action('wp_head', 'favicon');

Source: Display Gravatar Image as the Favicon (WPSnipp)

4. Add Theme Support for Featured Images

Before you do anything else, you’ll want to make sure that your theme supports featured images (previously known as post thumbnails). This is a really important step for image optimization in WordPress.

It almost certainly will, but if it doesn’t, just add the following code to functions.php:

add_theme_support( 'post-thumbnails' );

Source: Function Reference/add theme support (WordPress Codex)

5. Require a Featured Image Before You Can Publish a Post

As a rule of thumb, every one of your blog posts should have a featured image.

With that in mind, it can be especially useful to enforce the inclusion of a featured image; either if you run a multi-author blog and you want to make sure that your writers are adhering to your requirements, or if you run your own blog and tend to get a bit forgetful at times.

If you add the following code to your functions.php and try to publish a post that doesn’t have a featured image, you will receive the following message: “You must select a Featured Image before your Post can be published.”

add_action('save_post', 'wpds_check_thumbnail');
add_action('admin_notices', 'wpds_thumbnail_error');

function wpds_check_thumbnail($post_id) {

    // change to any custom post type 
    if(get_post_type($post_id) != 'post')
        return;
    
    if ( !has_post_thumbnail( $post_id ) ) {
        // set a transient to show the users an admin message
        set_transient( "has_post_thumbnail", "no" );
        // unhook this function so it doesn't loop infinitely
        remove_action('save_post', 'wpds_check_thumbnail');
        // update the post set it to draft
        wp_update_post(array('ID' => $post_id, 'post_status' => 'draft'));

        add_action('save_post', 'wpds_check_thumbnail');
    } else {
        delete_transient( "has_post_thumbnail" );
    }
}

function wpds_thumbnail_error()
{
    // check if the transient is set, and display the error message
    if ( get_transient( "has_post_thumbnail" ) == "no" ) {
        echo "<div id='message' class='error'><p><strong>You must select Featured Image. Your Post is saved but it can not be published.</strong></p></div>";
        delete_transient( "has_post_thumbnail" );
    }

}

Source: Require a Featured Image Before You Can Publish Post (WPSnipp)

6. Show Featured Images in Your WordPress Blog’s RSS Feed

By default, featured images are not shown in your blog’s RSS feed. This is no good at all, and is high on my list of must-change tasks when designing a new site and making WordPress work better with images.

Fortunately, the solution is simple enough. Just use the following code snippet:

add_filter('the_content_feed', 'rss_post_thumbnail');
function rss_post_thumbnail($content) {
  global $post;
  if( has_post_thumbnail($post->ID) )
    $content = '<p>' . get_the_post_thumbnail($post->ID, 'thumbnail') . '</p>' . $content;
  return $content;
}

Source: 10 Tips To Optimize Your WordPress Theme (Smashing Magazine)

7. Remove Paragraph Tags From Images in WordPress

One of the biggest irritations that I have with WordPress is its insistence on wrapping images in paragraph (i.e. <p></p>) tags. This can really cause havoc with styling, especially when you’re designing a theme.

Fortunately, it is easy enough to stop WordPress from doing this. Enter the code below and WordPress will remove paragraph tags surrounding images within the_content.

function filter_ptags_on_images($content){
    return preg_replace('/
\s*(<a>)?\s*(<img alt="" />)\s*(&lt;\/a&gt;)?\s*&lt;\/p&gt;/iU', '\1\2\3', $content);
}
add_filter('the_content', 'filter_ptags_on_images');</a>

Source: Remove P Tag From Around Images in the_content (WPSnipp)

8. Remove Width and Height from Inserted Images

By default, WordPress adds width and height attributes (in HTML) to each image that you insert into a blog post or page.

Under most circumstances this is desirable, as it ensures that the appropriate room is made for the image within your design, even if the image itself is still loading. However, there are times when these ‘hardcoded’ dimensions will directly contradict something you are trying to achieve with CSS.

If you ever find yourself in that quandary, just use the following code to remove the width and height attributes from your images in WordPress:

add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 );
add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 );

function remove_width_attribute( $html ) {
   $html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
   return $html;
}

Source: Remove Width and Height Attributes From Inserted Images (CSS Tricks)

9. Add Your Logo to the Login Page

Let’s finish off this roundup with a couple of backend branding snippets.

First we’ll add your logo to the WordPress login page (http://yoursite.com/wp-login.php). If you’re running a multi author blog or creating a website for a client, this will add a little extra sheen to the backend.

Just add the following code and upload your logo (feel free to change the file location to suit):

function my_custom_login_logo() {
    echo '
        h1 a { background-image:url('.get_bloginfo('template_directory').'/images/custom-login-logo.gif) !important; }
    ';
}

add_action('login_head', 'my_custom_login_logo');

Source: Customize WordPress Login Logo Without a Plugin (WPRecipes)

10. Add Your Logo to the Admin Page

If you’re going to add your logo to the login page, you may as well top things off by adding to the admin page too, right?

Just add the following code and upload your logo (again, feel free to change the file location to suit):

function custom_admin_logo() {
  echo '<style type="text/css">
          #header-logo { background-image: url('.get_bloginfo('template_directory').'/images/admin_logo.png) !important; }
        </style>';
}
add_action('admin_head', 'custom_admin_logo');

Source: Change Admin Logo (WP-Snippets)

What Next?

Above are the best image-related WordPress code snippets I could find, but they’re certainly not alone. Customization in WordPress is practically limitless, and there is a lot more that you can do than I’ve listed above.

With that in mind, do you have any favorite code snippets that you like to use? Or is there a specific function that we haven’t listed above that you would like to be able to use? Let us know in the comments section below!

Tom Ewer

Tom Ewer is a freelance blogger, longtime WordPress enthusiast and the founder of WordCandy. Find him at http://wordcandy.co
  • Thanks ! I noted all code And you wrote well.

  • Tim Kinnane

    Hey this is a great collection. I’ll definitely be using the feature image save check. I also just shared an article covering the various approaches to dynamically resizing images, when the theme needs to use an image size that wasn’t created on upload. The article is here https://medium.com/wordpress-continued/dynamic-image-downsize-610e16e71498 or just see the code: https://gist.github.com/timkinnane/e82eb87d9cc489620b80

  • Some of these list where the code goes, some do not. Can you fill us in on where they all go?

    • Beelal

      Themes functions.php file

  • Thanks for the include, I have to say that “Require a Featured Image Before You Can Publish Post” is one of my favs. Great list!

  • Al Guevara

    #7 caused an error in WordPress v4.41. I tested each one I used separately, and #7 failed.