SVG Support

Описание

Safely upload SVG files to your media library and use them like any other image. Now with optional sanitization!

But SVG Support has more features!!! Read on to learn more.

When using SVG images on your WordPress site, it can be hard to style elements within the SVG using CSS. Now you can, easily!

Scalable Vector Graphics (SVG) are becoming common place in modern web design, allowing you to embed images with small file sizes that are scalable to any visual size without loss of quality.

This plugin not only provides SVG Support like the name says, it also allows you to easily embed your full SVG file’s code using a simple IMG tag.

By adding the class "style-svg" to your IMG elements (or outer containers), this plugin dynamically replaces any IMG elements containing an SVG in the src that are found inside the target class with your complete SVG code, rendering it inline.

The main purpose of this is to allow styling and animation of your SVG elements. Usually your styling options are restricted when using embed, object or img tags alone.

Возможности

  • Поддержка SVG для Вашей медиабиблиотеки
  • Sanitize SVG uploads
  • Minify SVG files
  • Строчный вид кода SVG
  • Изменяйте элементы SVG используя CSS
  • Анимируй SVG элементы используя CSS и JsS
  • Очень простая страница настроек с инструкциями
  • Restrict SVG upload ability to Administrators only
  • Set custom target class (can be used on outer elements as of 2.4)
  • Extremely Simple To Use — Simplifies complex usage of SVG files

Использвание

Сперва установите и активируйте плагин Поддержка SVG (этот плагин).

После активации плагина, Вы можете загружать SVG изображения в библиотеку медиафайлов также просто как любые другие медиафайлы.

As an administrator, you can go to the admin settings page «Settings > SVG Support» and restrict SVG file uploads to administrators only.

Если Вам нужно загружать SVG файлы и использовать их только как изображения, то Вам не нужно включать «Расширенный режим». В этом случае неиспользуемые скрипты не будут подключаться и настройки будут скрыты.

Для продвинутых: Включите «Продвинутый режим» в Настройки > Поддержка SVG.

Now you can enable santization and/or minification of your SVG uploads, define a custom CSS class to target and fiddle with some other settings.

При включенном расширенном режиме, Вы можете настроить встраивание SVG изображений также как и обычные изображения с добавлением (в текстовом виде) класса "style-svg" (или любого другого Вашего класса) в Ваши теги IMG, если вы хотите, чтобы плагин заменил ваше изображение на подходящий SVG код.

Например:

<img class="style-svg" alt="alt-text" src="image-source.svg" />

или

<img class="your-custom-class" alt="alt-text" src="image-source.svg" />

The whole IMG tag element will now be dynamically replaced by the actual code of your SVG, making the inner content targetable.
This allows you to target elements within your SVG using CSS and JS.

Вы можете удалить все атрибуты из тега IMG, так как они в любом случае исчезнут.

Additionally, you can now add the target class to outer elements if you’re unable to add it directly to the IMG itself. This plugin will traverse the children looking for your SVG to replace with the inline code.

There’s a setting to automatically add your class to the IMG tag for you when you’re inserting SVG’s in to a post or page, which also removes unnecessary tags.

Since 2.3.11, you can force all SVG files sitewide to be rendered inline with a single checkbox (use with caution). Additionally, you can now choose whether to use the minified or expanded version of the JS file.

Избранные изображения: Если пост/страница сохранена с Вашим избранным изображением в формате SVG, то во вкладке избранного изображения будет опция для отображения этого SVG — строчным (только если активен расширенный режим).

На заметку: если Ваше SVG изображение не видно, то возможно оно отображается с нулевой высотой и шириной. Для корректного отображения Вам нужно задать свою высоту и ширину SVG изображению с помощью CSS.

If you’re having any issues, please use the support tab and I will try my best to get back to you quickly

Spin up a test site

With a single click, you can spin up a completely free test site to test SVG Support using TasteWP! No sign up, no cards, nothing! How cool is that? Give it a go:
Click Here to spin up a test site in seconds

Безопасность

As with allowing uploads of any files, there is potential risks involved. So I have added some features to help!

  • Optional sanitization to help strip any malicious code form your SVG files upon upload.
  • Restrict uploads to admin only.

Разрешайте пользователям загружать SVG-файлы только в том случае, если вы им доверяете. У вас есть возможность ограничить использование SVG только администраторами на странице настроек, а также включить очистку SVG, чтобы попытаться очищать все загружаемые файлы SVG.

По умолчанию любой, у кого есть доступ к медиатеке или права на загрузку, сможет загружать SVG-файлы (то есть администраторы, авторы и редакторы). Обратите внимание, что файлы SVG на самом деле являются XML, что теоретически позволяет злоумышленникам внедрять вредоносный код. Будьте осторожны с этим.

Отзывы

Я открыл для Вас отзывы и предложения — Спасибо за использование SVG Support!

Читайте @SVGSupport на Twitter
Читайте @benbodhi на Twitter

Note: I hope you like this plugin! Please take a moment to rate it.

Переводы

Вы можете помочь с переводом тут.
Ещё не переводили WordPress? Тогда прочитайте Translator Handbook и приступайте 🙂

Скриншоты

  • Основные настройки
  • Продвинутые настройки
  • Опция строчного SVG для избранных изображений
  • SVG используется во встроенном виджете изображении ( с версии выше 4.9)
  • Строчные SVG в коде фронтенда.
  • Help tab - Overview
  • Вкладка Помощь - Настройки
  • Вкладка Помощь- Стандартные Настройки
  • Help tab - Render SVG Inline (advanced usage)

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

SVG не встраивается строчно после обновления на версию 2.3

SVG Support 2.3 включает новую секцию настроек под названием «Расширенный режим». Пользователи, которые используют строчное встраивание SVG, должны убедиться что расширенный режим включен. Перейдите в Ваше панель администрирования > Настройки > SVG Support и поставьте галочку в пункте «Расширенный режим». Все предыдущие настройки будут там же.

Как отключить JavaScript во фронтенде, если я не использую строчный вид SVG?

Если Вы перейдете в Настройки и поддержка SVG в панели администратора, то Вы можете включить «Расширенный режим». Если Вы оставите его выключенным, то дополнительные возможности и скрипты не будут использоваться.

Я пытаюсь использовать SVG в настройщике темы, но у меня не получается.

To allow SVG to work in the customizer, you will need to modify/add some code in your child theme’s function file. Here is a great tutorial on how to do that. The important part is:

'flex-width'    => true
'flex-height'   => true

Как анимировать SVG?

You will need to edit your SVG file in a code editor so you can add CSS classes to each element you need to target within the SVG. Make sure that your IMG tag is being swapped out for your inline SVG and then you can use CSS or JS to apply animations to elements within your SVG file.

Почему Поддержка SVG не работает в многосайтовом режиме?

Если у Вас установлен multisite для WordPress 3.5, тогда Вам нужно удалить все ms-фалы. Здесь я перечислил ресурсы, которые могут вам помочь: Сброс ms-фалов Удаление ms-файлов после обновления версии 3.5.

Почему мои SVG не работают в Visual Composer?

If you are using SVG Support with Visual Composer or any other page builders, you will need to make sure that you can add your own class to the image. The easiest way to do this is by using a simple text or code block in the builder to put your image code in to. Additionally, there is now a setting to force all SVG files to be rendered inline.

Как я могу заставить это работать это вместе с плагином Media Library Assistant?

Для того чтобы плагин работал, Вам нужно добавить mime тип svg и svgz в: «Настройки MLA», «Медиабиблиотеку» и вкладку «Загрузки».

Отзывы

13.02.2024
Does exactly what it is supposed to do. It just works.
16.01.2024
It instantly adds the support of svg to worpress site and protects from svg+xml vulnearability
Посмотреть все 329 отзывов

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

«SVG Support» — проект с открытым исходным кодом. В развитие плагина внесли свой вклад следующие участники:

Участники

«SVG Support» переведён на 16 языков. Благодарим переводчиков за их работу.

Перевести «SVG Support» на ваш язык.

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

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

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

2.5.5

  • More error fixes and general clean up.

2.5.4

  • Fixed errors.

2.5.3

  • Fixed fatal php error.

2.5.2

  • Added some defaults for better security by default.

2.5.1

  • Added missing quotes in uninstall.php.

2.5

  • Cleaned up spelling mistakes and general formatting.
  • Addressed security concern.
  • Added more sanitization options — frontend and admin both supported.
  • Added support for SVG minification.
  • Added ability to choose jQuery or vanilla JS.
  • Added DB cleanup on uninstall.
  • Fixed dimensions fallback.

2.4.2

  • Fixed srcset warning for some premium themes.
  • Fixed original IMG IDs not getting preserved on replacement.
  • Removed some rogue text from featured image box.

2.4.1

  • Fixed issue causing WP-CLI to break.

2.4

  • NEW FEATURE: Added optional SVG sanitization.
  • NEW FEATURE: Added optional SVG minification.
  • Added inline SVG checkbox to Gutenberg featured image.
  • Better Gutenberg support in general.
  • Modified class targeting to allow inline rendering of nested SVGs (any level deep) when you can’t set the IMG class directly.
  • Modified JS to use vanilla JS instead of jQuery.
  • Fixed accessibility issues on settings page.
  • Fixed dimensions metadata issue.
  • Fixed division by 0 issue when SVG had no width or height set.
  • Fixed featured image spacing issue in both classic and block editor.
  • Bumped required PHP version.
  • Removed obsolete admin notice.
  • Removed srcset for SVG files.
  • Removed directory name from filepath metadata.

2.3.21

  • Fixed featured image SVG overlapping container.

2.3.20

  • Fixed admin setting not being escaped when output.

2.3.19

  • Fixed PHP Warning from localize_script in functions/enqueue.php.
  • Added a check for SRC attribute in js/svgs-inline.js.

2.3.18

  • Updated author URL in main plugin file.
  • Updated donate links.
  • Cleaned up plugin action meta links and settings page.
  • Rolled back a fix in functions/attachment.php due to it removing meta from other attachments.

2.3.17

  • Added setting to choose whether to load frontend CSS or not.

2.3.16

  • Fix for files that have the XML declaration.
  • Fix for PHP warnings from image widget.
  • Some small CSS changes to the frontend when displaying SVG media attachments.

2.3.15

  • Had to roll back a recent PHP warnings fix due to it breaking some theme compatibility.

2.3.14

  • Fixed: Fatal error in some cases when removing old option from the database.

2.3.13

  • Fixed: PHP warnings and notices from the image widget when using SVG files and wp_debug was on.
  • Modified: Better front end CSS for displaying SVG attachments, both as images and inline.
  • Removed: DB entry for deprecated admin notice.

2.3.12

  • Новое: встроенная вкладка Помощь работает с плагином на странице с Настройками
  • New: Wrapped the inline JS in a function so you can call it at will using bodhisvgsInlineSupport();.
  • Modified: Admin CSS to target SVG src only.
  • Modified: SVG Support settings page — cleaned it up a little.
  • Removed: Version update admin notice.

2.3.11

  • Новинка: Возможность использовать развёрнутый JS-файл вместо минифицированной/сжатой версии (полезно при использовании плагинов кеширования).
  • Новинка: опция принудительного встраивания строчного SVG. Эта опция позволяет выводить все ваши SVG-файлы независимо от применяемых классов. Имеется проблема, когда Вы не можете добавить свой класс изображения. Например, некоторые изображения редактора страниц. Также это касается изменения класса в настройках и необходимости изменения всех встроенных медиафайлов. Это позволяет просто принудительно выполнить рендер, а не обновлять все классы.
  • Небольшие изменения файла readme и описания.
  • Немного исправлен код functions/featured-image.php в строке 69 в ответ на предупреждение.
  • Обновление Требуемая версия» до 4.8 (при этом все должно работать на предыдущих версиях, в версии 4.7 были проблемы с ядром, пришло время обновиться для Вас).

2.3.10

  • Исправлены отсутствующие ссылки на странице настроек.

2.3.9

  • Изменена мета-ссылка для страницы настроек.
  • Изменены некоторые переводы в разных местах плагина.
  • Добавлена рекомендация для ShortPixel Image Optimization.
  • Добавлено условие для проверки типа поста, поддерживающего миниатюры, перед установкой мета-данных.

2.3.8

  • Added some CSS to make sure featured images show on WooCommerce products, Sensei Courses and Lessons.
  • Fix: Auto insert class setting was stripping featured image HTML in some cases.

2.3.7

  • Added WP version check to wrap mime fix function needed for WP v4.7.1 — v4.7.2.
  • Добавлено исправление MIME типов файлов.
  • Modified admin notice code to make it neater.
  • Fix: attachment-modal.php issues with some servers and external SVG files (props to @abstractourist & @malthejorgensen for providing fixes, as I could not consistently reproduce the issue).
  • Compatibility: Changed a line to provide wider compatibility, specifically for WordPress Bedrock on a LEMP stack.
  • Compatibility: Added another snippet to the JS to support IE11 (apparently people still use IE).
  • Добавлено больше Вопросов -ответов

2.3.6

  • New: Added polyfill to make svgs-inline.js work with older browsers.
  • New: Section to leave reviews on settings page.
  • Removed: Redundant one time upgrade activate code.
  • Fix: Errors reported on activation and on the settings page — Related Support Thread.

2.3.5

  • Revision and modification of the thumbnail display code.

2.3.4

  • Fix: Fatal error for some because a function wasn’t prefixed.

2.3.3

  • Fix: Missing arguments PHP warnings from new attribute control file.
  • Обновлен текст на странице настроек.

2.3.2

  • Modified the attribute control code that auto inserts our class to only apply to SVG files.

2.3.1

  • Fix: Fatal error in some cases due to admin notice.

2.3

  • New Feature — Advanced Mode: allows you to turn off the advanced features and simply upload SVG files like normal images. This addition also enables users to turn off the script added on front end by leaving Advanced Mode unchecked.
  • New Feature — Featured Image Support: If your featured image is SVG, once the post is saved you will see a checkbox to render the SVG inline (advanced mode only).
  • Улучшена производительность: изображение не заменяется на строчное, если это не SVG.
  • Added new stylesheet for settings page.
  • Moved SCSS files to their own folder.
  • Changed donate link so I can track it and properly thank you for your generous donations.
  • Added a rating link to the settings and media pages.
  • Почищен код, добавлено больше комментариев.
  • Добавлена проверка версии плагина.
  • Added notice so people are aware they may need to turn on the advanced mode.

2.2.5

  • FIX: Display SVG thumbnails in attachment modals.

2.2.4

  • FIX: Added function to temporarily fix an issue with uploading in WP 4.7.1

2.2.32

  • Changed text domain to match plugin slug for localization.

2.2.31

  • Attempt to fix ability to translate

2.2.3

  • Modified code in svg-support/js/svg-inline.js and svg-support/js/min/svg-inline-min.js to allow JS control of the SVG elements and detect if they have been loaded (IMG tag swapped out). Thanks to laurosello for this suggestion and code contribution.
  • Fixed SVG thumbnails not displaying correctly in list view of the media library.
  • Очищен код и добавлено немного комментариев.
  • Added translation for Spanish. Thanks to Apasionados del Marketing for the translation.

2.2.2

  • Changed another anonymous function in svg-support/functions/thumbnail-display.php that was causing errors for some.

2.2.1

  • Changed anonymous function in svg-support/functions/thumbnail-display.php line 15 to prevent fatal error in older PHP versions.

2.2

  • Added support to make SVG thumbnails visible in all media library screens.
  • Added SVGZ to the mime types.
  • Automatically removes the width and height attributes when inserting SVG files.
  • Added ability to choose whether the target class is automatically inserted into img tags or not, stripping the default WordPress classes.
  • Added ability to choose whether script is output in footer — true or false.
  • Blocked direct access to PHP files.
  • Добавлена поддержка SCSS используя CodeKit: minified CSS + JS файлы.
  • Updated spelling for incorrect function name.
  • Changed comment formatting across all files for consistency.
  • Добавлена ссылка на GoWebben на странице настроек, для поддержки автора в размере $25.
  • Протестировано в WordPress 4.3.
  • Обновлен файл Readme.

2.1.7

  • Протестировано в WordPress 4.0 и добавлены иконки плагина для нового интерфейса.

2.1.6

  • Added missing jQuery dependency in /functions/enqueue.php (pointed out by walbach) — was loading SVG Support JS before jQuery.

2.1.5

  • Добавлен перевод на Сербский язык, созданный Ogi Djuraskovic.

2.1.4

  • Исправлена ссылка на страницу настроек плагина (на странице плагина)
  • Добавлено больше ссылок — «Поддержка» и «Поддержать автора»
  • Изменен заголовок страницы настроек плагина.
  • Cleaned up settings page with CSS
  • Satisfied my OCD tendencies a little

2.1.3

  • Added plugin_action_links file for custom menus on plugin page.

2.1.2

  • Cleaned up trunk, tags and readme.txt to show correct changelog and update notice.

2.1.1

  • Fixed JS file conditional — worked in local testing but not live.

2.1

  • Updates to language files for localization.

2.0

  • Added an admin settings page with instructions plus options for restricting to admin use only and setting a custom CSS target class.
  • Whole plugin completely re-written and re-structured.
  • Добавлена опция, разрешающая загружать SVG только администраторам.
  • Добавлено поле для добавления произвольного CSS класса.
  • Добавлены стили страницы настроек плагина.

1.0

  • Initial Release.