我正在回答自己,因为今天我问了自己发布的2个问题,并花了一些时间找到答案。找到解决方案后,我想与他人共享它,但是任何其他解决方案都值得赞赏,并且我准备接受比我的发现更好的任何解决方案。最好不要修改和改进我的解决方案。
编辑
在Rarst回答之后,我已经编辑了代码。现在,函数使用标准dashicons类,但还允许在menu_icon
参数中指定旧样式的图像url,并在参数中指定全新的dashicons类menu_dashicon
。
工作流程
首先我以为是register_post_type
,触发一个动作,registered_post_type
将传递给挂钩函数的参数传递给钩子函数register_post_type
,而不对其进行过滤,因此可以为该函数创建自定义参数。
因此,我决定传递参数'menu_dashicon'
以传递自定义破折号。
之后,我想创建一个侦听该参数的类,将图标保存在类变量中。同一个班级可以负责
- 检查WP的当前版本,如果小于3.8,则什么也不做
- 如果版本是3.8+,则
$menu
在适当的钩子上循环数组,并:
- 删除通过
'menu_icon'
和添加的所有自定义图片(如果有)
- 根据通过
'menu_dashicon'
参数添加的内容添加内联样式
我将代码创建在一个文件中,通过这种方式,它可以轻松地包含在任何主题/插件中,甚至可以用作MU插件,然后,可以'menu_dashicon'
在安装的每个主题和/或插件中使用全新的参数。
我还添加了一个最小的插件标头,可以将其用作独立插件,但是使用起来可能不太有用。
如何使用
在内部register_post_type
只需传递'menu_dashicon'
带有dashicon类的值的参数(不带前缀'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图标类名称。
所以这里的代码:
<?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);
它也可以作为要点
两个CPT:使用Dashicons的“想法”和“图库”。注意使用不同的管理配色方案进行自动颜色更改。
menu_icon
则不能将图像url用于以前的版本...但是谁在乎过去?:)