Inline SVG Fallback In WordPress

- 1 answer

I'm building a WordPress theme which has an options panel. Within the options panel, admin can upload an icon which will appear in the footer.

When uploading an icon, admin will upload a SVG and PNG version to the media uploader (icon.svg and icon.png for example).

I'm displaying this icon on the front end like so:

<?php if( have_rows('footer_icons', 'option') ): ?>
    <?php while( have_rows('footer_icons', 'option') ): the_row();
        // Vars
        $icon = get_sub_field('icon');
            <img src="<?php echo esc_url($icon); ?>" alt="icon" width="60" height="60">
    <?php endwhile; ?>
<?php endif; ?>

Is there a way to feature detect and display an inline png fallback (icon.png) should the browser not support SVG? I know Modernizr offers SVG detection, but I couldn't see that it would offer this level of support.



I would question whether it's necessary at all. Browser support for SVG use in img tags is over 96% globally. Source:

If absolutely necessary add the PNG URL as a data attribute to the img tag with the source set to the SVG file. Load in Modernizr and use its feature detection to replace the image's source with the PNG URL if SVG images aren't supported.

Example markup (assumes $png_icon has been set):

<img src="<?php echo esc_url( $icon ); ?>" data-png-src="<?php echo esc_url( $png_icon ); ?>" alt="icon" width="60" height="60">

Further reading: (Example #4)