add_cssclass()
云策文档标注
概述
add_cssclass() 是一个 WordPress 函数,用于向字符串添加一个 CSS 类。它主要用于管理后台菜单的 CSS 类处理,简化类名拼接操作。
关键要点
- 函数接受两个参数:$class_to_add(要添加的 CSS 类)和 $classes(目标字符串),返回添加后的字符串。
- 如果 $classes 为空,函数直接返回 $class_to_add,避免空字符串问题。
- 函数定义在 wp-admin/includes/menu.php 中,主要用于后台管理菜单,前端使用可能受限或不推荐。
- 自 WordPress 2.7.0 版本引入,常用于 add_menu_classes() 等函数中。
代码示例
// 基本用法示例:向菜单项添加 CSS 类
$menu[0][4] = add_cssclass('menu-top-first', $top[4]);
// 用户贡献的示例:在菜单排序中动态添加类
$c = $menu[$lastm][4];
$menu[$lastm][4] = add_cssclass('menu-top-last', $c);注意事项
- 该函数主要针对后台管理菜单设计,前端使用需谨慎,可能需手动包含相关文件。
- 使用时需确保参数类型正确,避免非字符串输入导致错误。
原文内容
Adds a CSS class to a string.
Parameters
$class_to_addstringrequired-
The CSS class to add.
$classesstringrequired-
The string to add the CSS class to.
Source
function add_cssclass( $class_to_add, $classes ) {
if ( empty( $classes ) ) {
return $class_to_add;
}
return $classes . ' ' . $class_to_add;
}
Changelog
| Version | Description |
|---|---|
| 2.7.0 | Introduced. |
Skip to note 3 content
MakeWebBetter
Usage when working over menus order
$firstm = $lastm = false; $i = 0; foreach ( $menu as $order => $top ) { $i++; if ( 0 == $order ) { $menu[0][4] = add_cssclass( 'menu-top-first', $top[4] ); $lastm = 0; continue; } if ( 0 === strpos( $top[2], 'separator' ) && false !== $lastm ) { // if separator $firstm = true; $c = $menu[ $lastm ][4]; $menu[ $lastm ][4] = add_cssclass( 'menu-top-last', $c ); continue; } if ( $first ) { $c = $menu[ $order ][4]; $menu[ $order ][4] = add_cssclass( 'menu-top-first', $c ); $firstm = false; } $lastm = $order; }Skip to note 4 content
crstauf
While the function name does suggest no limitation on its availability, it is defined in
wp-admin/includes/menu.php, so is not immediately available on the frontend (and use on the frontend is probably discouraged).