Skip to content

Instantly share code, notes, and snippets.

@jonathantneal
Last active October 9, 2017 07:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathantneal/293f2c6d2ec96a79d024 to your computer and use it in GitHub Desktop.
Save jonathantneal/293f2c6d2ec96a79d024 to your computer and use it in GitHub Desktop.
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
Copy link

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