Adding a Base64-encoded SVG image as a WordPress admin menu icon
For our new plugin Kanban, we have a custom WordPress admin menu page. So of course I wanted to add a custom icon to it.
I looked a the Yoast SEO WordPress plugin which has a custom plugin, and discovered it wasn’t an image,but a Base 64 encoded svg image.
Great! I’d rather do that than deal with an image.
But frustratingly, you can find a lot about the WordPress dashicons as a font, but there’s not a lot written about using a Base 64 encoded svg image. On the add_menu_page WordPress documentation, there’s a reference to it, but not how to use it, or how big the image should be.
I finally wound up using the source from Yoast to find how they did it in their plugin.
The last problem was figuring out how big the image should be. Googling around, I found one article, and at the very bottom it said the icon should be 20 x 20.
It turns out that 20px x 20px is too big, but it’s close. I wound up cropping it down to 19px x 17px, with an extra couple pixels on the left to center it. I think it turned out well!
So to summarize:
- Make your image around 18px x 18px
- Use http://b64.io or https://www.base64-image.de to get your image as a Base 64 encoded string.
- Add it to your code:
// Base 64 encoded SVG image. $icon_svg = 'data:image/png;base64,iVBORw0...'; // base 64 string goes here add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_svg );