What's new

Welcome to aaohl | Welcome

Join us now to get access to all our features. Once registered and logged in, you will be able to create topics, post replies to existing threads, give reputation to your fellow members, get your own private messenger, and so, so much more. It's also quick and totally free, so what are you waiting for?

How to Improve WordPress Image Functionality

Hoca

Administrator
Staff member
Joined
Dec 14, 2023
Messages
979
Reaction score
0
Points
16
WordPress is great for website building, be it a professional website, a blog, an artistic blog or a Photographer’s showcase. But even with all the major updates and improvements done lately to it’s core, WordPress remains unchanged in the image management. In this tutorial we are going to change that.

WordPress handling of images is less than ideal, specially when you need to upload and handle tons of images a day. There are primary 2 major shortcomings that, as of today, are not fixed yet. Those two are:

  • WordPress is unable to link to your media file when you upload a picture. By default it links to the Page Attachment.
  • WordPress creates thumbnail images of each picture you upload, even when they are not used at all.

The Problems​

Linking to attachment pages​


First of all, WordPress thinks you will want to link to an attachment page whenever you upload and try to insert an image into your blog, but that’s really something very few people actually need. Linking to the attachment page only leads to an extra step for any reader to see your picture in a zoomed state.

Second, this behavior is long gone since by today’s standards, almost all sites introduce some form of gallery plugin, slider plugin or responsive image zoom plugin that will let you open the image in full screen easily. All of this plugins will need a direct link to the media file to work properly. The native WordPress default of linking to the attachment page will block zoom functionality in almost all plugins, forcing you to change the Link To property in each image to Media File.

The problem is that WordPress refuses to save your preference! So, instead of choosing the Link To Media File one time, you’re forced to do it every single time! Can you see the predicament?

Thumbnails​


The second big problem that WordPress incorporates, specially on sites with thousands of pictures is that, by default, WordPress will create scaled down versions (thumbnails) of each picture you upload into your WordPress, even when they are not used at all. This is bad because of 2 things:

  • It slows down the image upload on your blog.
  • It takes unnecessary space in your hosting account.

The first problem that arises because of the way WordPress handle the images comes partially from the theme configuration. WordPress reads the media formats for the theme you’re currently using and uses that to determine all the image thumb resizes that need to happen. Because themes usually have tons of different image thumb sizes depending on the posts types, this means that for every picture you upload, WordPress is creating at least 10 more scaled down thumbnail files. This also means that for a simple 10 picture gallery you create, you’ll have about 100 files added into your WordPress hosting account. Now, multiply that by the thousands of pictures you have on your blog and you’ll begin to understand why this is a major problem.

image-attach-media-00


The other important point to consider is that all of that scaling down occurs in realtime before the picture is available in your WordPress media gallery, which means that it will slow down the image upload a lot.

The Solutions​


Fortunately I’m here to help, as I will teach you how to properly remove those limitations and improve your WordPress media management functionality by doing 2 things:

  • Forcing WordPress to always link to media file instead of to the attachment page (no more clicking!)
  • Forcing WordPress to create image resizes only when they are actually needed, saving you tons of space.
attachment-page

This is a typical example of what happens when you click on an image and WordPress redirects you to its attachment page


The first thing we’ll do is create the necessary function for WordPress to select media file by default, this is done by adding the following code into your functions.php file in your theme.

function my_gallery_default_type_set_link( $settings ) {
$settings['galleryDefaults']['link'] = 'file';
return $settings;
}

add_filter( 'media_view_settings', 'my_gallery_default_type_set_link');

Once you add this function you reload your theme by disabling it and enabling it again. You’ll see that WordPress will start linking to your media file by default !!

image-attach-media-01


Now that we have WordPress behaving like it should, let’s force it to stop creating unnecessary files. Use this code:

add_filter( 'image_downsize', 'ml_media_downsize', 10, 3 );
function ml_media_downsize( $out, $id, $size ) {

$dims = null;
$crop = false;

if( is_array( $size ) ) {
// don't handle these for now. but if you want on-the-fly sizes, comment out
// the return statement
return false;
$dims = $size;
// create custom image size name consisting of widthXheight
$size = sprintf( "%dx%d", $size[0], $size[1] );
}

// If image size exists let WP serve it like normally
$imagedata = wp_get_attachment_metadata( $id );
if ( is_array( $imagedata ) && isset( $imagedata['sizes'][$size] ) )
return false;

// Check that the requested size exists, or abort
if ( $dims === null ){
global $_wp_additional_image_sizes;
if ( !isset( $_wp_additional_image_sizes[$size] ) )
return false;
}

// Make the new thumb
if( $dims ){

// we got passed custom width/height as array...
if ( !$resized = image_make_intermediate_size(
get_attached_file( $id ),
$dims[0],
$dims[1],
$crop ) ) {
return false;
}

} else {

if ( !$resized = image_make_intermediate_size(
get_attached_file( $id ),
$_wp_additional_image_sizes[$size]['width'],
$_wp_additional_image_sizes[$size]['height'],
$_wp_additional_image_sizes[$size]['crop'] ) ) {
return false;
}

}

// Save image meta, or WP can't see that the thumb exists now
$imagedata['sizes'][$size] = $resized;
wp_update_attachment_metadata( $id, $imagedata );

// Return the array for displaying the resized image
$att_url = wp_get_attachment_url( $id );
return array( dirname( $att_url ) . '/' . $resized['file'], $resized['width'], $resized['height'], true );

}

add_filter('intermediate_image_sizes_advanced', 'ml_media_prevent_resize_on_upload');
function ml_media_prevent_resize_on_upload( $sizes ) {
// Removing these defaults might cause problems, so we don't, though you could
// probably set them to all be the same dimensions and rely on custom image sizes
// for everything else
return array(
'thumbnail' => $sizes['thumbnail'],
'medium' => $sizes['medium'],
'large' => $sizes['large']
);
}

The code is not mine and it´s available in the net.

Now that we have the functionality implemented, how about creating a plugin out of this so we don’t have to mess with the functions.php file?

Create your own plugin​


To create your own plugin, this is what you need to do:

  1. Create a folder named yourpluginname.
  2. Create a php file with the same name of your plugin folder: yourpluginname.php.
  3. Create a standard header for WordPress to read the plugin properly.
  4. Paste your code.
  5. Compress the contents of the folder with the folder name inside.
  6. Upload it into your WordPress like any normal plugin.
  7. Enjoy your new skill !

This is how the header looks like while you code your own plugin, I seriously recommend you to use Notepad++ which is very friendly to work with and free:

thetechieblog-plugin


Now, this is how the code should look like, once it’s added onto the php file:



<?php
/**
* Plugin Name: Link Image to Media and reduce Thumb creation
* Plugin URI: https://wpthemedetector.com
* Description: Force WordPress to always link to the media file and rescale on the fly when needed
* Author: Alex Vojacek
* Author URI: https://alexvojacek.com
* Version: 0.1.2
*/

add_filter( 'media_view_settings', 'my_gallery_default_type_set_link');
function my_gallery_default_type_set_link( $settings ) {
$settings['galleryDefaults']['link'] = 'file';
return $settings;
}

add_filter( 'image_downsize', 'ml_media_downsize', 10, 3 );
function ml_media_downsize( $out, $id, $size ) {

$dims = null;
$crop = false;

if( is_array( $size ) ) {
// don't handle these for now. but if you want on-the-fly sizes, comment out
// the return statement
return false;
$dims = $size;
// create custom image size name consisting of widthXheight
$size = sprintf( "%dx%d", $size[0], $size[1] );
}

// If image size exists let WP serve it like normally
$imagedata = wp_get_attachment_metadata( $id );
if ( is_array( $imagedata ) && isset( $imagedata['sizes'][$size] ) )
return false;

// Check that the requested size exists, or abort
if ( $dims === null ){
global $_wp_additional_image_sizes;
if ( !isset( $_wp_additional_image_sizes[$size] ) )
return false;
}

// Make the new thumb
if( $dims ){

// we got passed custom width/height as array...
if ( !$resized = image_make_intermediate_size(
get_attached_file( $id ),
$dims[0],
$dims[1],
$crop ) ) {
return false;
}

} else {

if ( !$resized = image_make_intermediate_size(
get_attached_file( $id ),
$_wp_additional_image_sizes[$size]['width'],
$_wp_additional_image_sizes[$size]['height'],
$_wp_additional_image_sizes[$size]['crop'] ) ) {
return false;
}

}

// Save image meta, or WP can't see that the thumb exists now
$imagedata['sizes'][$size] = $resized;
wp_update_attachment_metadata( $id, $imagedata );

// Return the array for displaying the resized image
$att_url = wp_get_attachment_url( $id );
return array( dirname( $att_url ) . '/' . $resized['file'], $resized['width'], $resized['height'], true );

}

add_filter('intermediate_image_sizes_advanced', 'ml_media_prevent_resize_on_upload');
function ml_media_prevent_resize_on_upload( $sizes ) {

// Removing these defaults might cause problems, so we don't, though you could
// probably set them to all be the same dimensions and rely on custom image sizes
// for everything else
return array(
'thumbnail' => $sizes['thumbnail'],
'medium' => $sizes['medium'],
'large' => $sizes['large']
);

}

You can change the header data for your name, author’s website, etc.

This will remove the need for you to add the code in the functions.php of your theme, and it will allow you to install this plugin in as much sites as you want, without having to touch a single line of code in your theme.

Now let’s upload the plugin, in my case it’s called: thetechieblogoptim.

Once uploaded directly from WordPress you can see it installed in the plugins folder:

thetechieblog-plugin-01


And this is how it looks from the plugin’s page:

thetechieblog-plugin


Now that the plugin is active, your WordPress is actively using media file as the default attachment for all the images, and you just saved 1 click for each image you upload. It’s also uploading the images without the theme’s image thumbs files and creating them only when needed, saving you tons of space and increasing your image upload speed.

Wrapping Up​


Today you’ve learned two big shortcomings of WordPress that may be affecting you and your site, you’ve learned how to improve it and also how to make a plugin out of it. This knowledge will help you create new plugins with added functionality too. Now enjoy your new skill and post any doubts you may have in the comments below.

The post How to Improve WordPress Image Functionality appeared first on WordPress Theme Detector.
 
Top Bottom