Custom svg admin menu icon in WordPress

2020-02-22 06:13发布

I'm really counting on your help in this one. I searched a lot and found no solution. I want to have a custom icon for my plugin in admin menu, and I want it to integrate well with the color scheme.

I looked here https://codex.wordpress.org/Function_Reference/add_menu_page Under $icon_url

(WP 3.8+) If 'data:image/svg+xml;base64...', the specified SVG data image is used as a CSS background

However, if I put a URL to an SVG icon there, all I get is an img with SVG in its src attribute, so it doesn't integrate at all with the color scheme. It's supposed to be a CSS background.

Also, I don't understand this data:image/svg+xml;base64... What does it mean exactly?

I tried embedding inline SVG in the $icon_url but obviously, it won't work, but I just had to try it.

Dashicons are not an option, there's no icon there suitable for my project.

6条回答
The star\"
2楼-- · 2020-02-22 06:13

I got the solution by analyzing Woocommerce. If no url is supplied to the add_menu_page function, WordPress uses the default dashicon. So it's just a matter of overriding the default style. Like add this to admin styles:

#adminmenu #toplevel_page_yourpageid .menu-icon-generic div.wp-menu-image:before {
    font-family: your_font !important;
    content: '\eiconid';
    font-size: 1.3em!important;
}

I converted svg to font on Icomoon.

查看更多
3楼-- · 2020-02-22 06:22

Step by Step example using FontAwesome:

Including color and custom post types

查看更多
我命由我不由天
4楼-- · 2020-02-22 06:29

The svg file must have the fill attribute set in it to work. Open the svg file in an editor like Atom, and make sure it looks like this:

<path fill="black" d="....

You can put any kind of color you want in there, WordPress uses JS to automatically update the fill value based on the admin theme.

查看更多
可以哭但决不认输i
5楼-- · 2020-02-22 06:31

You have to paste a Base64 encoded image (data URI), into the src...

More on Wikipedia.

查看更多
何必那么认真
6楼-- · 2020-02-22 06:32

After you have converted the icondata in base 64, correct way to put it is like this;

The "," is important

'data:image/svg+xml;base64,'.$icon_data_in_base64
查看更多
对你真心纯属浪费
7楼-- · 2020-02-22 06:37

Just thought I should add the following:

To get the SVG to automatically re-colour to match the theme, it needs to have a fill attribute set. This is because it's dynamically altered through script, and it otherwise won't know what part to re-colour.

查看更多
登录 后发表回答