Converter for Media — Optimize images | Convert WebP & AVIF

Описание

Speed up your website using our ease image optimizer by serving WebP and AVIF images. By replacing files in standard JPEG, PNG and GIF formats with WebP and AVIF formats, you can save over a half of the page weight without losing quality.

After installing the plugin you do not have to do anything more. Your current images will be converted into a new format. When image optimization by our image optimizer is finished, users will automatically receive new, much lighter images than the original ones.

As of today, over 90% of users use browsers that support the WebP format. The loading time of your website depends to a large extent on its weight and the level of image optimization. Using our WebP Converter, now you can and speed up it in a few seconds without much effort!

This will be a profit both for your users who will not have to download so much data, but also for a server that will be less loaded. Remember that a better optimized website also affects your Google ranking. Image optimization is very important.

AVIF support

Now in the PRO version you can use AVIF as the output format for your images. The AVIF format is a new extension — is the successor to WebP. AVIF allows you to achieve even higher levels of image compression, and the quality of the converted images after image optimization is better than in WebP.

Как это работает?

  • If you have just installed the plugin, you can optimize images with one click. Image size will be smaller after generate webp!
  • New images that will be added to the Media Library will be converted automatically.
  • Our image optimizer does not modify your original images in any way. This means security for you and your files.
  • When the browser loads an image, our plugin checks if it supports the WebP format. If so, the image in WebP format is loaded.
  • The plugin does not make redirects in default mode, so the URL is always the same. Only the MIME type of the image changes to image/webp.
  • No redirects means no cache issues, faster and trouble-free operation of your website. If you want to know more about how it works, check out the plugin FAQ below.
  • It does not matter if the image display as an img HTML tag or you use background-image. It works always!
  • In case rewriting by rules from .htaccess file is blocked, a mode is available which loads images via PHP file. Then image URLs are changed, but the logic of operation is the same as in the case of the default mode.
  • The final result after image optimization is that your users download less than half of the data, and the website itself loads faster!
  • You lose nothing — if you had to remove the plugin, it will remove everything after itself. It does not leave any trace, so you can check it with ease.

Convert WebP — it is the future of image optimization!

Поднимите свой сайт на новый уровень сейчас! Установите плагин и наслаждайтесь сайтом, который загружается быстрее. Конечно, вы и ваши пользователи это оценят.

Поддержка дополнительных каталогов

You can convert WebP and optimize images not only from /uploads directory but also from /plugins and /themes directories. This allows full integration with the WebP format!

Поддержка разработки плагина

Мы часами работаем над разработкой этого плагина. Техническая поддержка также требует много времени, но мы делаем это, потому что хотим предложить вам лучший плагин. Мы наслаждаемся каждой новой установкой плагина.

If you would like to appreciate it, you can try the PRO version. In addition, you will gain access to extra functionalities that will allow you to achieve even better image optimization results.

Пожалуйста, прочитайте FAQ ниже. Спасибо за то, что вы с нами!

Скриншоты

  • General tab of the plugin settings
  • Advanced tab of the plugin settings
  • Bulk optimization of images
  • Optimization statistics of Media Library

Установка

  1. Upload the plugin files to /wp-content/plugins/webp-converter-for-media directory, or install the plugin through the WordPress plugins screen directly.
  2. Activate the plugin through Plugins screen in WordPress Admin Panel.
  3. Use Settings -> Settings -> Converter for Media screen to configure the plugin.
  4. Click on the button Start Bulk Optimization and wait.
  5. Check if everything works fine using this tutorial.

Вот и все! Ваш сайт уже загружается быстрее!

Часто задаваемые вопросы

Как получить техническую поддержку? (прежде чем обратиться за помощью)

Before you add a new thread, read all other questions in this FAQ and other threads in the support forum first. Perhaps someone had a similar problem and it has been resolved.

При добавлении темы выполните следующие действия и ответьте на каждый из них:

1. Do you have any errors on the plugin settings page? Please read this thread if you have any errors.

2. URL of your website.

3. Screenshot of the Help Center tab on the plugin settings screen — please take a screenshot of the ENTIRE page.

4. Please do the test, which is described in the FAQ in the question «How to check if the plugin works?». Please send a screenshot of Devtools with the test results.

Please remember to include the answers to all questions by adding a thread. It is much easier and accelerates the solution of your problem.

Ошибка на экране настроек плагина?

If you have an error on the plugin settings screen, first of all, please read it carefully. They are displayed when there is a problem with the configuration of your server or website.

The messages are designed to reduce the number of support requests that are repeated. It saves your and our time. Please read this thread for more information.

Ошибка при конвертации?

Вы можете получить несколько типов ошибок при конвертации. Прежде всего, внимательно прочитайте их содержание. По большей части вы можете решить эту проблему самостоятельно. Попробуйте сделать это или обратитесь к администратору сервера.

Если вы получили ошибку: Файл "%s" не существует. Пожалуйста, проверьте путь к файлу. означает, что file_exists () работает в PHP вернул false , используя путь к файлу, указанный в сообщении об ошибке. Проверьте этот путь и убедитесь, что он правильный.

Если вы получили сообщение об ошибке: Файл "%s" не читается. Проверьте права доступа к файлам. означает, что функция is_readable () в PHP вернул false , используя путь к файлу, указанный в сообщении об ошибке.
Проверьте разрешения для файла и каталог, в котором находится файл.

If you get an error: "%s" is not a valid image file. means that the file is damaged in some way. Download the file to disk, save it again using any graphics program and add it again to the page. If the error applies to individual images then you can ignore it — just the original images will load, not WebP.

If you get an error: Image "%s" converted to .webp is larger than original and converted .webp file has been deleted. means the original image weighed less than WebP. This happens when images have been compressed before. Disable the «Automatic removal of files in output formats larger than original» option in plugin settings to force always using WebP.

Какие требования к плагину?

Practically every hosting meets these requirements. You must use PHP at least 7.0 and have the GD or Imagick extension installed. The extension must support WebP format. If you have an error saying that the GD or Imagick library is not installed, but you have it installed then they are probably incorrectly configured and do not have WebP support.

Это обязательные расширения PHP, используемые WordPress для создания миниатюр. На вашем сервере также должны быть включены модули mod_mime, mod_rewrite and mod_expires.

An example of the correct server configuration can be found here. The link to your current configuration can be found in the Help Center tab on plugin settings screen.

Note the items marked in red. If the values marked in red do not appear in your case, it means that your server does not meet the technical requirements. Pay attention to the WebP Support value for the GD library and WEBP in the list of supported extensions for the Imagick library.

In a situation where your server does not meet the technical requirements, please contact your server Administrator. We are not able to help you. Please do not contact us about this matter, because this is a server configuration problem, not a plugin.

Also, REST API must be enabled and work without additional restrictions. If you have a problem with it, please contact the Developer who created your website. He should easily find the issue with the REST API not working.

How to check if the plugin works?

You can find more information on how the plugin works in our manual.

How to change the path to uploads?

Это возможно при использовании следующих типов фильтров для изменения путей по умолчанию. Это решение для продвинутых пользователей. Если нет, пропустите этот вопрос.

Путь к корневому каталогу установки WordPress (по умолчаниюABSPATH):

add_filter( 'webpc_site_root', function( $path ) {
    return ABSPATH;
} );

Paths to directories (relative to the root directory):

add_filter( 'webpc_dir_name', function( $path, $directory ) {
    switch ( $directory ) {
        case 'uploads':
            return 'wp-content/uploads';
        case 'webp':
            return 'wp-content/uploads-webpc';
        case 'plugins':
            return 'wp-content/plugins';
        case 'themes':
            return 'wp-content/themes';
    }
    return $path;
}, 10, 2 );

Обратите внимание, что каталог /uploads-webpc должен находиться на том же уровне вложенности, что и /uploads , /plugins и /themes каталоги.

Префикс в URL-адресе /wp-content/ каталога или эквивалентного (используется в .htaccess):

add_filter( 'webpc_htaccess_rewrite_path', function( $prefix ) {
    return '/';
} );

Для следующего примера пользовательской структуры WordPress:

...
├── web
    ...
    ├── app
    │   ├── mu-plugins
    │   ├── plugins
    │   ├── themes
    │   └── uploads
    ├── wp-config.php
    ...

Используйте следующие фильтры:

add_filter( 'webpc_site_root', function( $path ) {
    return 'C:/WAMP/www/project/web'; // your valid path to root
} );
add_filter( 'webpc_htaccess_rewrite_path', function( $prefix ) {
    return '/';
} );
add_filter( 'webpc_dir_name', function( $path, $directory ) {
    switch ( $directory ) {
        case 'uploads':
            return 'app/uploads';
        case 'webp':
            return 'app/uploads-webpc';
        case 'plugins':
            return 'app/plugins';
        case 'themes':
            return 'app/themes';
    }
    return $path;
}, 10, 2 );

After setting the filters go to Settings -> Converter for Media in the admin panel and click the Save Changes button. .htaccess files with appropriate rules should be created in the directories /uploads and /uploads-webpc.

How to exclude paths from converting?

To exclude selected directories, use the following filter:

add_filter( 'webpc_supported_source_directory', function( bool $status, string $directory_name, string $server_path ): bool {
    $excluded_directories = [ 'my-directory' ];
    if ( in_array( $directory_name, $excluded_directories ) ) {
        return false;
    }
    return $status;
}, 10, 3 );

To exclude selected files use the following filter (in this case with the suffix «-skipwebp» in a filename, e.g. image-skipwebp.png):

add_filter( 'webpc_supported_source_file', function( bool $status, string $file_name, string $server_path ): bool {
    $excluded_suffix = '-skipwebp';
    if ( strpos( $file_name, $excluded_suffix . '.' ) !== false ) {
        return false;
    }
    return $status;
}, 10, 3 );

Argument $server_path is the absolute server path to a directory or file. Inside the filters, you can apply more complicated rules as needed.

Filters run before images are converted — they no longer support converted images. You have to delete them manually if they should not be converted.

Support for custom directories

The plugin supports the following directories by default:
/gallery
/plugins
/themes
/uploads

If you want to add support for a custom directory, add the following code to the functions.php file in your theme directory (use a correct directory name instead of custom-directory):

add_filter( 'webpc_source_directories', function ( $directories ) {
    $directories[] = 'custom-directory';
    return $directories;
} );

Remember that this directory must be located in the /wp-content directory.

Как запустить конвертацию вручную?

By default, all images are converted when you click on the Start Bulk Optimization button. In addition, conversion is automatic when you add new files to your Media Library.

Помните, что наш плагин учитывает изображения, сгенерированные WordPress. Существует множество плагинов, которые генерируют, например, изображения другого размера или другой версии.

Если вы хотите интегрироваться со своим плагином, который генерирует изображения самостоятельно, вы можете сделать это. Наш плагин предоставляет возможность такой тип интеграции. Это работает для всех изображений в каталоге /wp-content.

Это решение для продвинутых пользователей. Если вы хотите интегрироваться с другим плагином, лучше всего связаться с автором этого плагина и предоставить ему информацию о действиях, доступных в нашем плагине. Это поможет вам быстрее найти решение.

You can manually run converting selected files, you can use the action to which you will pass an array with a list of paths (they must be absolute server paths):

do_action( 'webpc_convert_paths', $paths );

Альтернативный метод — начать преобразование выбранного вложения вручную, передав идентификатор сообщения из библиотеки мультимедиа. Не забудьте запустить это действие после регистрации всех размеров изображения (т.е. после запуска функции add_image_size ) :

do_action( 'webpc_convert_attachment', $post_id );

Argument $paths is array of absolute server paths and $skip_exists means whether to skip converted images.

You can also modify the list of image paths for an attachment, e.g. to exclude one image size. To do this, use the following filter:

add_filter( 'webpc_attachment_paths', function( $paths, $attachment_id ) {
    return $paths;
}, 10, 2 );

Аргумент $paths — массив абсолютных путей к серверу, а $attachment_id — идентификатор поста, добавленного в медиатеку.

Чтобы удалить файлы, конвертированные вручную, используйте следующее действие, предоставив в качестве аргумента массив абсолютных серверных путей к файлам (это приведет к удалению файлов, конвертированных вручную) :

do_action( 'webpc_delete_paths', $paths );

Support for WP-CLI

The plugin supports WP-CLI, which enables faster image conversion from the server level. More information on how to get started with WP-CLI can be found in the Handbook. The supported commands are described below.

Checking how many maximum images for conversion are on website:

wp webp-converter calculate

Converting all images:

wp webp-converter regenerate

Converting all images (with «Force convert all images again» option):

wp webp-converter regenerate -force

Плагин поддерживает CDN?

The website files (WordPress files) and the images from the Media Library must be on the same server. If they are, everything should work fine.

If only your images are on another CDN server, unfortunately correct operation is impossible, because such images are managed by another server.

Конфигурация для Nginx

For Nginx server that does not support .htaccess rules, additional Nginx server configuration is required for the plugin to function properly.

Find the configuration file in one of the paths (remember to select configuration file used by your vhost):
/etc/nginx/sites-available/ or /etc/nginx/sites-enabled/
/etc/nginx/conf.d/

and add this code (add these lines at the beginning of the server { ... } block)remember to add these rules before any other location {} rules:

# BEGIN Converter for Media
set $ext_avif ".avif";
if ($http_accept !~* "image/avif") {
    set $ext_avif "";
}

set $ext_webp ".webp";
if ($http_accept !~* "image/webp") {
    set $ext_webp "";
}

location ~ /wp-content/(?<path>.+)\.(?<ext>jpe?g|png|gif|webp)$ {
    add_header Vary Accept;
    expires 365d;
    try_files
        /wp-content/uploads-webpc/$path.$ext$ext_avif
        /wp-content/uploads-webpc/$path.$ext$ext_webp
        $uri =404;
}
# END Converter for Media

Then add support for the required MIME types, if they are not supported. Edit the configuration file:
/etc/nginx/mime.types

and add this code (add these lines inside the types { ... } block):

image/webp webp;
image/avif avif;

After making changes, remember to restart the machine:

systemctl restart nginx

In case of problems, please contact us in the support forum. We will try to help.

Отзывы

28.09.2022
Seems like it optimized all the images well, especially heavy PNGs, one of them for example went from 1000KB (almost 1MB) to 68KB. However, it stayed as a PNG, and it didn't change to WEBP. Browsers and Google will not still think it's a PNG file. Ideally it should convert & replace the path in posts and pages to the new WEBP extension.
28.09.2022
The problem I was experiencing was quickly responded to. I got a lot in return for the service I purchased. I can't thank you enough. It definitely works and I recommend it.
27.09.2022
Works a treat. I like that converted images are stored in a seperate folder and the originals are not tampered with.
Посмотреть все 650 отзывов

Участники и разработчики

«Converter for Media — Optimize images | Convert WebP & AVIF» — проект с открытым исходным кодом. В развитие плагина внесли свой вклад следующие участники:

Участники

«Converter for Media — Optimize images | Convert WebP & AVIF» переведён на 16 языков. Благодарим переводчиков за их работу.

Перевести «Converter for Media — Optimize images | Convert WebP & AVIF» на ваш язык.

Заинтересованы в разработке?

Посмотрите код, проверьте SVN репозиторий, или подпишитесь на журнал разработки по RSS.

Журнал изменений

5.2.4 (2022-09-27)

  • [Changed] Messages displayed during bulk optimization of images
  • [Added] Debug information about registered image sub-sizes

5.2.3 (2022-09-23)

  • [Added] Debug information about disabled functions

5.2.2 (2022-09-15)

  • [Fixed] Closing of admin notice

5.2.1 (2022-09-14)

  • [Fixed] Deleting converted files during plugin uninstallation

5.2.0 (2022-09-10)

  • [Fixed] Re-conversion of images modified after previous conversion
  • [Added] Optimization statistics in Media Upload Popup
  • [Added] Filter webpc_source_directories to add support for custom directories

5.1.0 (2022-08-28)

  • [Fixed] Exclusion of converted files from backup generated by UpdraftPlus plugin
  • [Added] Optimization statistics in Media Library

5.0.1 (2022-08-26)

  • [Removed] Filter webpc_uploads_prefix
  • [Fixed] Calculating number of images to convert in WP-CLI
  • [Fixed] Converting files that contain plus sign in filename
  • [Changed] Notification asking to clear cache for LiteSpeed
  • [Added] Exclusion of converted files from backup generated by All-in-One WP Migration plugin
  • [Added] Exclusion of converted files from backup generated by UpdraftPlus plugin
  • [Added] Exclusion of converted files from backup generated by BackWPup plugin

5.0.0 (2022-08-20)

  • [Changed] Information about plugin operation and technical support on plugin settings page
  • [Changed] Labels of options in plugin settings
  • [Changed] Option field for configuration of quality level
  • [Changed] Widget for conversion process
  • [Added] Filter webpc_htaccess_cache_control_private to disable Cache-Control as private
  • [Added] Statistics on number of converted images
  • [Added] Tabs for plugin settings

See changelog.txt for previous versions.