Connecting WordPress thumbnails, setting them up and using them.

Almost any site in certain moment time faced with the need to create thumbnails for many images. There are many reasons for this. Starting from the desire to add pictures to various lists, as, for example, when displaying the latest materials. Finishing with writing my own galleries and catalogs.

The main problem is not so much that it is necessary to create a miniature for each picture. This can be easily done using a program for batch file processing, and subsequently, when filling, add pictures with thumbnails. How much is that, with a high probability, you may need pictures different sizes. It is simply impossible to predict in advance all the required dimensions. This is why a tool is needed to automatic change image sizes and creating thumbnails, which will solve both problems at once: creating thumbnails in automatic mode and forming any size upon request.

Note: If you decide to resize pictures, CSS help, then there is one waiting for you unpleasant surprise. It's a matter of position disk space pictures. For example, if you display a 100Kb image on a website and install it in CSS property width is set to "50px", then, despite the fact that the image will look small, it will still occupy 100Kb. You probably already understand how much extra traffic will go through every time a page with at least a dozen of these thumbnails is opened.

Note: Most ready-made modules already contain built-in mechanisms for automatic creation miniatures and it might seem that using these mechanisms would be the easiest way out. However, in most cases, these mechanisms either have hard-wired settings that are not easy to change or put into a separate settings block, or use other parts of the module, or are evenly distributed throughout the module (their code is scattered across different files).

Writing a tool to automatically create thumbnails

Note: If you are not interested in the creation steps and you need a ready-made module, then proceed to the next section, “Configuring the script.”

Before you start writing a tool, you need to decide on a minimum set of requirements. After some time you will have a list like this:

  • Uniqueness of thumbnail names. When you have a lot of articles or products, there is a high probability that there will be at least two images with the same names. You can also simply sort pictures into catalogs without worrying about the uniqueness of names.
  • Support different types pictures. Basically, these are gif, png and jpg.
  • Dynamic Dimensions. At any given time, you may need different thumbnail sizes. For example, you have slightly changed the layout for displaying list items and you need to change the size of the thumbnails. This action must be decided simple change parameter in url.
  • Caching images. Pictures must not only be physically created on disk (since resizing an image takes time), but also cached by the browser (each request for a picture is an extra request). And also the pictures themselves must be periodically re-created. After all, it is possible that some pictures have been changed since the creation of the miniatures.
  • Ability to quickly delete all thumbnails. All miniatures should be stored in one place. Otherwise, banal cleaning of the site from extra files or the need to massively recreate miniatures will cause you some difficulties.
  • Ease of implementation. The script should be easy to embed on any website and use minimum set basic functions php language

Once the requirements have been determined, you can begin writing.

Create a file called "thumb.php" and add the first block - a block with parameters:

This block defines the following parameters: directory for storing thumbnails, size (width) restrictions and its default value, result caching time, default identifier value. If most of the parameters are clear, then the identifier parameter needs to be explained. The identifier is used to separate pictures with the same names from each other. An integer ID is available almost everywhere; every article and every product has it. In extreme cases, it is quite simple to determine.

Note: The image resizes proportionally, so it is enough to use only the width of the thumbnail.

Now, you need to decide on the names of the parameters and the link template, as well as implement a block for reading parameter values ​​and checking them. We make the link template as follows:

  • site.ru/thumb.php?&&

Note: Short names are chosen for simplicity. You can change the names of the parameters, but then you will have to adjust the code a little.

Define a block:

// Check for the presence of a parameter with the full path to the image if (isset($_GET["f"])) $f = (string) $_GET["f"]; // If there is no parameter, then exit else exit; // Get information about the path $path_parts = pathinfo($f); // Get the parent directory where // the image is stored $path_images = $path_parts["dirname"]; // Get the full name of the image $f = $path_parts["basename"]; // Parse the file name $image_filename = basename($f,".".$path_parts["extension"]); $image_extension = $path_parts["extension"]; // Check that the name of the picture consists of symbols, dashes and numbers // You can remove this check, // for example, if you use Cyrillic if (!preg_match("/^((1,100))$/", $ f)) exit; // Get the file width if (isset($_GET["s"])) $s = (int) $_GET["s"]; else $s = $size_def; // Check the minimum thumbnail size limit if ($s< $size_min) $s = $size_min; // Проверяем ограничение максимального размера миниатюры if ($s >$size_max) $s = $size_max; // Use the article id as a unifier if (isset($_GET["id"])) $id = (int) $_GET["id"]; else $id = $id_def; // Identifier cannot be negative if ($id< 0) $id = $id_def;

Now, just in case, you need to check the presence of a function to determine the mime type. And if there isn’t one, then create your own:

// Check for the presence of a function to get the type if (!function_exists("mime_content_type")) ( function mime_content_type($f) ( $extension = pathinfo($f, PATHINFO_EXTENSION); $extension = strtolower($extension); switch ($extension ) ( case "jpg": case "jpeg": return "image/jpeg"; break; case "png": case "gif": return "image/". $extension; break; ) ) )

Now, we create a block that checks whether such a thumbnail exists and whether its lifetime has expired. If successful, we send the image to the client:

// Form the physical path to the thumbnail $file_thumb = $_SERVER["DOCUMENT_ROOT"] . "/" . $path_thumbs. $image_filename ."-thumb-" . $id . "-" . $s ".". $image_extension; // If the file with the thumbnail exists if (file_exists($file_thumb)) ( $cache_modified = time() - @filemtime($file_thumb); // If the image caching time has not expired, // then return the image if ($cache_modified< $cache_lifetime) { // Время последнего изменения header("Last-Modified: ". gmdate("D, d M Y H:i:s", filemtime($file_thumb)) ." GMT", true, 200); // Длина header("Content-Length: ". filesize($file_thumb)); // Тип header("Content-Type: ". mime_content_type($file_thumb)); // Кэширование header("Cache-Control: public"); header("Expires: " . date("r", @filemtime($file_thumb) + $cache_lifetime)); echo file_get_contents($file_thumb); exit; } }

Now, we write a block that creates a thumbnail for the picture, based on all the received parameters.

// Form the physical path to the image $file_image = $_SERVER["DOCUMENT_ROOT"] . "/" . $path_images "/". $f; // If the image exists, // then create a thumbnail if (file_exists($file_image)) ( // Get the file size and type $is = getimagesize($file_image); // If the file is not an image, // then return nothing if ($is === false) exit; // In accordance with the type, we get the image switch ($is) ( case 1: $image = imagecreatefromgif($file_image); break; case 2: $image = imagecreatefromjpeg($file_image) ; break; case 3: $image = imagecreatefrompng($file_image); break; default: break; $is > $s) ( $th_width = $s; $th_height = floor($is * $coefficient); $thumb = imagecreatetruecolor($th_width, $th_height); imagecopyresampled($thumb, $image, 0, 0, 0 , 0, $th_width, $th_height, $is, $is ) // Otherwise, we give the image “as is” // Note: Enlarging the image in most cases will make it ugly // Therefore, it is better to replace the image that is too small and then replace it. its big. // For example, a 16x16 picture is unlikely to produce a normal 200x200 picture else ( $thumb = $image;) // Save the file according to the type switch ($is) ( case 1: imagegif($thumb, $file_thumb); break; case 2: imagejpeg($thumb, $file_thumb); case 3: imagepng($thumb, $file_thumb); break; exit; break; ("D, d M Y H:i:s", filemtime($file_thumb)) ." GMT", true, 200); header("Content-Length: ". filesize($file_thumb)); header("Content-Type: ". mime_content_type($file_thumb)); header("Cache-Control: public"); header("Expires: " . date("r", time() + $cache_lifetime)); echo file_get_contents($file_thumb); )

The result is a small tool that dynamically creates and caches thumbnails with unique names in one directory, supports different image formats, and is easy to implement. Thus, the PHP script fully fulfills all the requirements.

Setting up a PHP script to automatically resize images

Note: If you skipped the section “Writing a tool” or did not create a file, you can download the finished file here: thumb.zip

Copy the resulting file to the location where you wish. For example, in the "utils" folder. Then start setting up. Open the file and overwrite the default settings:

  • $path_thumbs - path to the folder for storing thumbnails (default path is "images/thumbs/"). Don't forget to create this directory.
  • $size_min - minimum thumbnail width in pixels (default 1).
  • $size_def - default thumbnail width in pixels (default 40)
  • $size_max - maximum size in pixels of the thumbnail (default 1600)
  • $cache_lifetime - cache time for each thumbnail in seconds (default 84000 * 30, i.e. thirty days)
  • $id_def - default identifier value (default 0). The ID is used to create unique thumbnail names.

After making the settings, the PHP script for automatic resizing can already be used. To do this, recall the template once again:

  • site.ru/utils/thumb.php?&&

An example of a real request would look like this:

  • site.ru/utils/thumb.php?id= 15 &s= 100 &f= images/razdel-1/statya-15/start.png

However, in the era of using beautiful CNC links, such a request will look somewhat ugly. Therefore, you need to add the following lines to the ".htaccess" file in the root of the site (provided that the hosting supports mod_rewrite and that the .htaccess file has a line with "RewriteEngine On"):

#Add lines after the line "RewriteEngine On" #Thumbs RewriteRule ^thumb/((1,11))/((1,11))/(.*) utils/thumb.php?id=$1&s=$2&f=$3

  • site.ru/thumb/ (Identifier)/(Width)/(Full path to image)

After this, an example of a real request would look like this:

  • site.ru/thumb/15/100/images/razdel-1/statya-15/start.png

Thumbnails are essentially duplicates of images on the site. Therefore, you may need to configure the robots.txt file. Of course, search engines should respond adequately to the existence of thumbnails, and not consider this an attempt to manipulate search results. However, if you doubt this, then it is worth adding the following lines to the rules in robots.txt (provided that thumb.php is in the utils folder):

Disallow: /thumb/ Disallow: /utils/thumb.php

Now, you have a great tool for automatic image resizing in PHP, which dynamically creates and caches thumbnails with unique names in one directory, supports different image formats and is easily implemented on any site.

You can download the finished tool here:


We'll talk about wordpress thumbnails. Or, as they can also be called, image previews. In this article, you can find out what a WordPress thumbnail is, how to connect it to your theme if it is not connected, how to configure its display, and also in what cases it can be used on your site?

And so as not to delay, we will immediately begin to examine all the issues listed above.

What is a WordPress thumbnail and where can I use it?

A WordPress thumbnail is a smaller copy of an image on a website that uses the Wordpress engine for administration; otherwise it can be called an image preview or a mini picture.

It can be used both in article announcements, instead of standard images, and in other areas of the site, for example, when using popular or similar WordPress posts with a picture. There are also plugins that can use image previews to display various information. In addition, a mini picture can be added to the RSS feed of our website for a more attractive appearance of article announcements. In general, the scope of miniatures is quite wide, and questions related to this type of image often arise.

For example, very often questions arise related to the fact that some plugin or display code uses thumbnails, but they do not appear on the site, which makes the appearance completely different from what was expected. In this case, you need to check the support of thumbnails in our theme, and if it is missing, enable it.

Checking WordPress theme support for thumbnails.

So, if we are not sure about the connection of thumbnails in the theme, this can be easily checked. To do this, you need to go to the WordPress admin panel and go to the editor of any of the posts, or select the “add new” post item.

If WordPress thumbnails are connected, then in the right column we will see a window called “Post Thumbnail”, with a link to “Set Thumbnail”.

If we don’t see this window, we should check that there is no option to add a thumbnail in the screen settings. To do this, in the upper right corner, you need to click on the “Screen Settings” tab. And check that the “Post Thumbnail” item is missing.

If this item is present, you just need to check the box next to the item and then a window will appear where we can set the article thumbnail. If this item is not available, then we need to enable thumbnail support in our template.

And please note that due to the way themes are translated, this option may be called differently, for example, “Characteristic image,” and the link to create a thumbnail may be like this: “Set a special image.”

Connecting a WordPress thumbnail and displaying it in the article announcement.

To connect WordPress thumbnails to our theme, you need to open the functions.php file in the admin panel, or using the NotePad++ text editor and at the very bottom, before?>, add the following code:

Add_theme_support("post-thumbnails");

After that, in the post editor we will have the opportunity to set a thumbnail. And if we don’t have very many articles, then we can set, for each, wordpress thumbnail by hand.

Now how can I use it in an article announcement? To display a thumbnail home page, you need to write the code in the index.php or loop.php file:

If you are having trouble finding the right place, then just find this code:

Or like this:

And before it, insert the code for displaying the WordPress thumbnail.

After these steps and assigning a mini image in the editor wordpress posts, small copies of the images will appear on the main page. Plus, we can make this image a link to the continuation of the article. To do this, let's replace standard code, to this one:

" title="!}">

A little more detail about what this code consists of:

  • 1. opening tag , and closing— a tag intended for creating links. It is he who will make the thumbnail a link.
  • 2.href="" - link to the article.
  • 3. title="" — тайтл (заголовок) ссылки, который будет виден, при наведении на нее курсора. Берется из заголовка статьи.!}
  • 4. — mini-image output function.

Now it should be a little clearer how this works. All we have to do is design the appearance of the picture, depending on our needs. To do this, you need to add the following code to style.css if it is not there:

Img.wp-post-image(thumbnail styles here)

And between the brackets, instead of “here are the thumbnail styles,” add the necessary styles. This applies to normal, standard output, without using any parameters.

WordPress thumbnail options.

But this function has additional parameters for more flexible configuration. Of course, we will not consider all the parameters, but will only touch upon the assignment of sizes for mini pictures, since this may be needed when adjusting the appearance of the images. And when assigning parameters to the thumbnail display function, we will be able to change the sizes from the admin panel, which is more convenient than going into the code and editing it every time.

By default, we can use the following options for images:

The_post_thumbnail(); // standard output, without parameters, which we talked about above. the_post_thumbnail("thumbnail"); // a smaller copy of the image (default 150px x 150px). It is possible to configure from the admin panel, but the size should not exceed 150px the_post_thumbnail("medium"); // medium size (default 300px x 300px). Ability to configure from the admin panel. the_post_thumbnail("large"); // large size (default 640px x 640px). Ability to configure from the admin panel. the_post_thumbnail("full"); // full size (original image size). the_post_thumbnail(array(100,100)); // your sizes. It is possible to assign any width and height dimensions.

To use one of the options, it is enough to replace the standard code (without parameters) with any of the proposed ones.

And accordingly, for each parameter, there are selectors for the css style file.

Img.wp-post-image img.attachment-thumbnail img.attachment-medium img.attachment-large img.attachment-full

The choice of the direct selector depends on the choice of parameters for the thumbnail.

Automatically assign a WordPress thumbnail and display it in the article announcement.

But what if the site has a fairly impressive list of content and setting the thumbnail manually will be quite problematic. To do this, we can use another function that will automatically create a mini-image from the first image of the article. To do this, in the functions.php file, after ?> add the function:

/i", $post->post_content, $matches); $first_img = $matches; return $first_img; ) ?>

Now, to display a thumbnail in the announcement of the article, that is, on the main page, open the file index.php or loop.php and add the code with the function for displaying the thumbnail (the function from the previous example can be removed) in the same place as with standard output:

"src="" alt="" width="150" /> !}

Now, let's take a little look at what this code consists of.

  • 1. Tag — in fact, it is this tag that will display the image, since the function itself only pulls out the link to the first image from the post.
  • 2. title="" — тайтл (заголовок) изображения, который можно увидеть при наведении курсора на миниатюру записи wordpress.!}
  • 3.src="" - a link to the image that will be displayed. As you can see, this is where the function is located, which is responsible for the link to the mini image.
  • 4. alt="" — альтернативный текст изображения. В случаях, когда в браузере отключена загрузка изображений, будет появляться alt, как бы описывая, что здесь должно быть за изображение.!}
  • 5. width="150" — sets the width of the thumbnail. In this case, the image will be reduced in direct proportion, focusing on the specified width.

It is quite possible that when you insert this code, two images will appear on the main page for each announcement. The result of this error might be to use the standard output of the announcement:

And for this error to disappear, just replace it with:

After this, this problem should disappear.

The last thing we can do today is to make the WordPress thumbnail a link. To do this, simply wrap the code with the tag with a link to the article:

" >"src="" alt="" width="150" /> !}

Regarding the use of WordPress thumbnails in the article announcement, that’s basically it. But we may also need to design the appearance of the picture using the style.css file. Some people may have trouble deciding which selectors to use for styling.

To design a mini image displayed using this method, you can simply add a class for the tag . For example, for the code to look like this:

" >"src="" alt="" width="150" /> !}

Img.mini(miniature styles here)

That's it. Now you can connect support for thumbnails to your template and use them to display article announcements. And also, design WordPress thumbnails as you wish.

The most important! Before any editing of the code, be sure to do so that you always have the opportunity to restore it.

That's all I have. Good luck!

Continuing the topic of WordPress thumbnails, I want to look at a very useful plugin that can greatly facilitate work in some situations. Imagine that you have been blogging for several years, say, you started somewhere in 2009, and now you want to modernize the appearance (template) by adding modern options to the site, for example, the same ones. Considering that support for thumbnails in WordPress was introduced much later, your pictures, apparently, are located inside the article directly in the text.

It turns out that you have 2 options for solving the problem - use or manually create thumbnails for each article. In the first case, there is a feeling of a “forced” and not entirely optimal solution, the second may even force you to spend 4-5 hours fiddling with pictures. Fortunately, I recently found a third option - Auto Post Thumbnail plugin.

This module allows you to generate thumbnails from the first image in the text for any blog posts or custom post types. If the first image is not found, the plugin will automatically continue searching until a thumbnail is created. In the event that thumbnails is already set for recording, simply nothing will happen. In short, the principle of operation is extremely simple and logical. By the way, if for some reason you want to prohibit the formation of a thumbnail for a particular post, then create a custom field (custom field) skip_post_thumb in the corresponding post.

Installing the plugin is simple and is done as a whole: the classic method by downloading the module files from the official website, unpacking it and uploading it to FTP in the /wp-content/plugins/ directory, followed by activation in the “Plugins” section from the admin panel; or in the “Add plugin” menu item, look for a module called “Auto Post Thumbnail”, where you download and activate it. That's it!

After installation, you will have a new menu item - Auto Post Thumbnail, where there is only one button to get started - Generate Thumbnails. There is also a note that I mentioned above - before launching, they ask you to set arbitrary skip_post_thumb fields for posts where you do not want to generate anything. If there are none, just click on the button.

You will be informed about the progress of processing all blog posts using a special status bar. Once processing is complete, you will see a corresponding notification. Similar auto-generation of thumbnails is carried out when changing, but Regenerate Thumbnails is used for these purposes.

You can go through the posts to make sure that this plugin works correctly. I also advise you to check the appearance of the blog and how correctly the posts are displayed. There is a possibility that for the selected WordPress template, you have added thumbnail display in your code by default. The result will be something like this (when both the image from the post and the thumbnail are displayed):

The first thing you might think about is that you need to remove pictures from posts. But don’t rush to do this, otherwise you end up with extra work again - you could initially not launch the plugin, but go through all the blog articles manually, changing the image to a thumbnail. In order to correct these errors, we will simply make some changes to the template.

First, open the files that are responsible for displaying the list of blog posts - index.php, home.php or archive.php, catagory.php, tag.php, where we find the text display function the_content(I mentioned it in the post about) and change it to:

This code will display a short announcement of a blog post without highlighting or images, in text form only. Further in the template file for displaying the full text of the note (single.php), on the contrary, we find the the_post_thumbnail thumbnail function and delete it. Typically, it is output with the following code:

"alignleft post_thumbnail" ) ) ; ) ?>

"alignleft post_thumbnail")); ) ?>

As a result, it should turn out that all pages with news lists will display thumbnails + short text, and full posts will display all the design and images that you specify in the editor. The solution, I think, is quite flexible, and the Auto Post Thumbnail plugin works great! By the way, if you buy websites and sometimes have to remake obvious GS into more or less beautiful projects, this module will definitely come in handy - I can say from personal experience. Although, in principle, there is another option for solving the problem - but there is more code and you need to navigate it better.