Search code examples
wordpressimagesvgadvanced-custom-fields

Output SVG as code instead of image tag in WordPress


I'm using Advanced Custom Fields to upload images to my site. After allowing SVG as filetype, I want to output the uploaded SVG image as "code". The template should output the <svg> tag with all the paths.

At the moment I'm using the following code to show the <img> tag:

<?php 

$image = get_field('image');

if( !empty($image) ): ?>

    <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />

<?php endif; ?>

I also tried to get the ID or use the URL to print out the <svg> tag. But it doesn't work. Any ideas how I could get the code?


Solution

  • I found a working answer here https://code.mukto.info/html-img-tag-to-html-svg-tag-wordpress/, just applied it to my project - everything works like charm.

    Also I copied the jQuery code below, just don't forget to set a class "SVG" for your IMG tag.

    /** Image to SVG **/
    // chage img tag class to svg or other
    $("img.svg").each(function () {
        var $img = $(this);
        var imgID = $img.attr("id");
        var imgClass = $img.attr("class");
        var imgURL = $img.attr("src");
    
        $.get(
            imgURL,
            function (data) {
                // Get the SVG tag, ignore the rest
                var $svg = $(data).find("svg");
    
                // Add replaced image's ID to the new SVG
                if (typeof imgID !== "undefined") {
                    $svg = $svg.attr("id", imgID);
                }
                // Add replaced image's classes to the new SVG
                if (typeof imgClass !== "undefined") {
                    $svg = $svg.attr("class", imgClass + " replaced-svg");
                }
    
                // Remove any invalid XML tags as per http://validator.w3.org
                $svg = $svg.removeAttr("xmlns:a");
    
                // Check if the viewport is set, else we gonna set it if we can.
                if (!$svg.attr("viewBox") && $svg.attr("height") && $svg.attr("width")) {
                    $svg.attr("viewBox", "0 0 " + $svg.attr("height") + " " + $svg.attr("width"));
                }
    
                // Replace image with new SVG
                $img.replaceWith($svg);
            },
            "xml"
        );
    });