我之所以回答自己,是因为今天我问了自己贴出的两个问题,并花了一些时间寻找答案。一旦我找到了解决方案,我想与大家分享,但任何其他解决方案都会受到高度重视,我愿意接受任何我发现比我更好的解决方案。欢迎您对我的解决方案进行编辑和改进,并鼓励您这样做。
编辑后Rarst 回答我已经编辑了代码。现在函数使用标准dashicons类,但是also 允许在中指定旧式图像urlmenu_icon
参数和一个全新的dashicons类menu_dashicon
论点
工作流我首先想到的是register_post_type
, 启动操作,registered_post_type
, 将参数传递给挂钩函数register_post_type
, 无需过滤它们,因此可以为该函数创建自定义参数。
所以我决定通过辩论\'menu_dashicon\'
传递自定义dashicon。
之后,我想创建一个侦听该参数的类,将图标保存在类变量中。同一类可以负责
检查WP的当前版本,如果小于3.8,则不执行任何操作,如果版本为3.8以上,则循环$menu
在适当的挂钩上排列,并删除通过以下方式添加的任何自定义图像(如果存在)\'menu_icon\'
并根据通过添加的内容添加内联样式\'menu_dashicon\'
param我在一个文件中创建代码,这样它就可以轻松地包含在任何主题/插件中,甚至可以用作MU plugin 然后你就可以使用全新的\'menu_dashicon\'
安装的每个主题和/或插件中的参数。
我还添加了一个最小的插件头,允许将其作为独立的插件使用,但这可能是不太有用的使用方式。
如何在内部使用register_post_type
只需通过\'menu_dashicon\'
具有dashicon类值的参数(without 前缀“dashicons-”):
$args = array(
...
\'menu_dashicon\' => \'chart-pie\', // dashicons will be used in WP 3.8+
\'menu_icon\' => $url_of_the_icon // icon images will be used in WP 3.7.1 & previous
);
register_post_type(\'my_cpt\', $args);
仅此而已。从中获取Dashicons图标类名
its site.
代码如下:
<?php
/**
* Plugin Name: GM CPT Icon
*/
namespace GM;
class CptIcon {
public static $cpt;
public $css;
static function registerIcon( $cpt, $icon ) {
self::$cpt[$cpt] = $icon;
}
function init() {
if ( $this->mp6() ) {
\\add_action(\'admin_menu\', array($this, \'parseMenu\') );
}
}
function mp6() {
return \\version_compare( $GLOBALS[\'wp_version\'], \'3.8\', \'>=\' );
}
function parseMenu() {
if ( $this->mp6() && ! empty( self::$cpt ) ) {
foreach ( $GLOBALS[\'menu\'] as $i => $item ) {
if $item[1] === \'edit_posts\' && (strpos($item[2], \'edit.php?post_type=\') === 0)) {
$this->menuItemClass($i, str_replace(\'edit.php?post_type=\', \'\', $item[2]));
}
}
}
}
function menuItemClass( $i, $type ) {
if ( \\in_array($type, \\array_keys(self::$cpt), TRUE ) ) {
$GLOBALS[\'menu\'][$i][4] = str_replace(\'menu-icon-post\', \'\', $GLOBALS[\'menu\'][$i][4]);
$GLOBALS[\'menu\'][$i][6] = \'dashicons-\' . self::$cpt[$type];
}
}
}
\\add_action(\'plugins_loaded\', function() {
if ( \\is_admin() && !( \\defined(\'DOING_AJAX\') && \\DOING_AJAX ) ) {
$cpticon = new CptIcon;
$cpticon->init();
}
});
\\add_action(\'registered_post_type\', function( $post_type, $args ) {
if ( isset($args->menu_dashicon) && ! empty($args->menu_dashicon) ) {
CptIcon::registerIcon($post_type, $args->menu_dashicon);
}
}, 10, 2);
它还可以作为
Gist<小时/>
两个CPT:“;“想法”;和;“画廊”;使用虚线图标。请注意使用不同的管理配色方案自动更改颜色。
<小时/>