仅将自定义类附加到导航菜单项

时间:2016-02-29 作者:nickpish

我在复习this extremely helpful post 从nav菜单中清除WP生成的类和ID,并找到RevelationTravis\'s option-- 请参阅下面的代码——这是一种有效地“白名单”某些菜单类的好方法。然而,我想知道是否有一种方法可以保留通过WP菜单管理面板指定的自定义导航菜单类,即“CSS类(可选)”,而不必按名称明确列出它们?

<?php
//Deletes all CSS classes and id\'s, except for those listed in the array below
function custom_wp_nav_menu($var) {
    return is_array($var) ? array_intersect($var, array(
        //List of allowed menu classes
        \'current_page_item\',
        \'current_page_parent\',
        \'current_page_ancestor\',
        \'first\',
        \'last\',
        \'vertical\',
        \'horizontal\'
        )
    ) : \'\';
}
add_filter(\'nav_menu_css_class\', \'custom_wp_nav_menu\');
add_filter(\'nav_menu_item_id\', \'custom_wp_nav_menu\');
add_filter(\'page_css_class\', \'custom_wp_nav_menu\');

//Replaces "current-menu-item" with "active"
function current_to_active($text){
    $replace = array(
        //List of menu item classes that should be changed to "active"
        \'current_page_item\' => \'active\',
        \'current_page_parent\' => \'active\',
        \'current_page_ancestor\' => \'active\',
    );
    $text = str_replace(array_keys($replace), $replace, $text);
        return $text;
    }
add_filter (\'wp_nav_menu\',\'current_to_active\');

//Deletes empty classes and removes the sub menu class
function strip_empty_classes($menu) {
    $menu = preg_replace(\'/ class=""| class="sub-menu"/\',\'\',$menu);
    return $menu;
}
add_filter (\'wp_nav_menu\',\'strip_empty_classes\');
?>
感谢您的帮助。

1 个回复
最合适的回答,由SO网友:bonger 整理而成

是的,它们存储为元数据\'_menu_item_classes\' 对于每个菜单项,例如(updated to use separate function)

function custom_wp_nav_menu_css_class( $classes, $item, $args, $depth ) {
    $whitelist = array(
        //List of allowed menu classes
        \'current_page_item\',
        \'current_page_parent\',
        \'current_page_ancestor\',
        \'first\',
        \'last\',
        \'vertical\',
        \'horizontal\'
    );
    // Note array containing empty entry always created for menu item meta so filter out.
    if ( $optional = array_filter( get_post_meta( $item->ID, \'_menu_item_classes\', true ) ) ) {
        $whitelist = array_merge( $whitelist, $optional );
    }
    return array_intersect( $classes, $whitelist );
}
add_filter( \'nav_menu_css_class\', \'custom_wp_nav_menu_css_class\', 10, 4 );

相关推荐

无法将设置添加到“NAV_MENUS”定制器面板

我试图在自定义程序的“菜单”面板中添加一个复选框,但由于某些原因,它没有显示出来。如果我尝试将其从“nav\\u菜单”更改为“title\\u tagline”或“colors”,复选框会显示得很好。是什么阻止它显示在“菜单”面板上?// add custom options to the Customizer function nssra_customizer_options($wp_customize) { // add \"menu primary flex\" checkb