Skip to content

Instantly share code, notes, and snippets.

@jonathantneal
Last active Oct 9, 2017
Embed
What would you like to do?
Using an SVG Icon System in WordPress with Grunt

Using an SVG Icon System in WordPress with Grunt

  1. Add grunt-svgstore to your build tool:

    npm install grunt-svgstore --save-dev
  2. Create an svgstore task in Grunt (like tasks/options/svgstore.js):

    module.exports = {
        main: {
            files: {
                'assets/svg/symbol-defs.svg': ['assets/svg/src/*.svg']
            },
            options: {
                cleanup: true,
                prefix : 'icon-'
            }
        }
    };

    Screenshot of built SVG file

  3. Leverage a shortcut function in PHP (like svg_icon):

    <?php
    
    function svg_icon( $name, $opts = array() ) {
        $href = WPTHEME_TEMPLATE_URL . '/assets/svg/symbol-defs.svg#icon-' . $name;
    
        $role = empty( $opts['role'] ) ? 'presentation' : $opts['role'];
    
        $class = empty( $opts['class'] ) ? 'icon icon-' . $name : 'icon ' . $opts['class'];
    
        $label = ' aria-label="' . ( empty( $opts['label'] ) ? $name : $opts['label'] ) . '"';
    
        $label = $role === 'presentation' ? '' : $label;
    
        return sprintf( '<svg role="%s" class="%s"%s><use xlink:href="%s"/></svg>', $role, $class, $label, $href );
    }
    
    // Usage: echo svg_icon( 'home' )
    //        echo svg_icon( 'home', array( 'class' => ' icon-home icon--active' ) )
    //        echo svg_icon( 'home', array( 'role' => 'img', 'label' = 'My home' ) )
    
    ?>
  4. Add support for Internet Explorer with SVG4Everybody:

    <?php
    
    wp_enqueue_script(
        'wptheme-svg4everybody',
        'https://cdnjs.cloudflare.com/ajax/libs/svg4everybody/2.0.3/svg4everybody.js',
        array(),
        WPTHEME_VERSION,
        true
    );
    
    // Add `svg4everybody()` to your theme JavaScript
    // Make your theme JavaScript depend on 'wptheme-svg4everybody'
    
    ?>
@allenmoore

This comment has been minimized.

Copy link

@allenmoore allenmoore commented Feb 10, 2016

The sprintf arguments should be escaped:

return sprintf( '<svg role="%s" class="%s"%s><use xlink:href="%s"/></svg>', esc_attr( $role ), esc_attr( $class ), esc_attr( $label ), esc_url( $href ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment