fekioh
fekioh

Reputation: 996

How to add inline svg as wordpress menu icons

I have a secondary nav on the sidebar with inline svg icons. I can change their color on hover with CSS. Here's the markup

<ul class="icons">
<li>
    <a href="index.php?page_id=39">
        <div class="icon-box tool-box"><!-- inline svg here... --></div>
        <h2>our tools</h2>
    </a>
</li>  <!-- and so on... -->

I was wondering if it would be possible to somehow add inline svg's through the wordpress wp_nav_menu function to make the menu easy to manipulate by the client. I can of course add the icons as background-images but then I cannot target them on hover...

Thanks

Upvotes: 5

Views: 4128

Answers (1)

bramchi
bramchi

Reputation: 810

You could use the wp_nav_menu_items filter to search & replace a certain string that you manually insert into the label of a menu item in the menus section of Wordpress.

For example:

  1. Add the %FANCY_SVG% string to a menu item label in the Wordpress admin.
  2. Define the filter as follows:
function find_replace_my_fancy_svg( $items, $args ) {
    $items = str_replace(
        '%FANCY_SVG%', 
        '<svg width="27" height="27" xmlns="http://www.w3.org/2000/svg"><g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"><g transform="translate(-15 -18)" fill="red"><path id="Rectangle" d="M15 18h27v27H15z"/></g></g></svg>',
        $items
    );
    
    return $items;
}
add_filter( 'wp_nav_menu_items', 'find_replace_my_fancy_svg', 10, 2 );

Upvotes: 5

Related Questions