Guenni007

replace-svg

Sep 27th, 2021 (edited)
550
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.97 KB | None | 0 0
  1. <?php
  2.  
  3.  
  4. // replace every svg with its inline code
  5. function replace_img_if_svg_with_inline_svg() {
  6. ?>
  7. <script type="text/javascript">
  8. (function($) {
  9.   $('img').filter(function() { return this.src.match(/.*\.svg$/); }).each(function(){
  10.     var imgSVG    = $(this);
  11.     var imgURL    = $(this).attr('src');
  12.     var imgAlt    = $(this).attr('alt');
  13.     var imgTitle  = $(this).attr('title');
  14.     var imgClass  = $(this).attr('class');
  15.     $.get(imgURL, function(data) {
  16.     var svg = $(data).find('svg');
  17.     // Remove invalid XML tags - but most svgs need that setting
  18.      // svg = svg.removeAttr('xmlns xmlns:xlink');
  19.     // add replaced image's alt tag to the inline SVG
  20.     typeof imgAlt === 'undefined' || imgAlt === '' ?  (svg = svg.attr('alt', 'Replaced Image')) : (svg = svg.attr('alt', imgAlt)) ;
  21.     // add replaced image's Title tag to the inline SVG
  22.     typeof imgTitle === 'undefined' || imgTitle === '' ? (svg = svg.attr('title', 'A SVG Image replaced by its inline code')) : (svg = svg.attr('title', imgTitle));
  23.     // Add replaced image's classes to the new SVG and add replaced-svg as new class
  24.     typeof imgClass === 'undefined' || imgClass === '' ? (svg = svg.attr('class', 'replaced-svg')) : (svg = svg.attr('class', imgClass+' replaced-svg'));
  25.     // check where the logo is placed : left or right or centered in the header
  26.     if ($(imgSVG).parents('.logo').length && $('html').hasClass('html_logo_left')) {
  27.       svg.attr('preserveAspectRatio', 'xMinYMid meet');
  28.     };
  29.     if ($(imgSVG).parents('.logo').length && $('html').hasClass('html_logo_right')) {
  30.       svg.attr('preserveAspectRatio', 'xMaxYMid meet');
  31.     };
  32.     if ($(imgSVG).parents('.logo').length && $('html').hasClass('html_logo_center')) {
  33.       svg.attr('preserveAspectRatio', 'xMidYMid meet');
  34.     };
  35.     // Replace image with inline SVG Code
  36.         imgSVG.replaceWith(svg);
  37.     }, 'xml');
  38. });
  39. })(jQuery);
  40. </script>
  41. <?php
  42. }
  43. add_action('wp_footer', 'replace_img_if_svg_with_inline_svg');
Add Comment
Please, Sign In to add comment