简体   繁体   English

WordPress菜单中的自定义活动菜单项

[英]Custom active menu item in wordpress menu

I have a wordpress theme using wp_nav_menu() to build the menu. 我有一个使用wp_nav_menu()构建菜单的wordpress主题。 I have a custom menu item in this menu that goes to a non-standard wordpress page. 我在此菜单中有一个自定义菜单项,该菜单项转到非标准的wordpress页面。 Is there a way I can conditionally set this nav item to current based on a match in the url string? 有没有一种方法可以根据url字符串中的匹配项将此导航项有条件地设置为current?

Thanks 谢谢

You can use the nav_menu_css_class in Wordpress to achieve the result you're after. 您可以在Wordpress中使用nav_menu_css_class来获得所需的结果。 Using this hook you can alter an array of CSS classes that can be applied to the menu. 使用此挂钩,您可以更改可应用于菜单的CSS类数组。

add_filter( 'nav_menu_css_class', 'add_parent_url_menu_class', 10, 2 );

function add_parent_url_menu_class( $classes = array(), $item = false ) {
    // Get current URL
    $current_url = current_url();
    // Get homepage URL
    $homepage_url = trailingslashit( get_bloginfo( 'url' ) );
    // Exclude 404 and homepage
    if( is_404() or $item->url == $homepage_url ) return $classes;
        if ( strstr( $current_url, $item->url) ) {
            // Add the 'parent_url' class
            $classes[] = 'parent_url';
        }
    return $classes;
}

function current_url() {
    // Protocol
    $url = ( 'on' == $_SERVER['HTTPS'] ) ? 'https://' : 'http://';
    $url .= $_SERVER['SERVER_NAME'];
    // Port
    $url .= ( '80' == $_SERVER['SERVER_PORT'] ) ? '' : ':' . $_SERVER['SERVER_PORT'];
    $url .= $_SERVER['REQUEST_URI'];

    return trailingslashit( $url );
}

This method will ignore 404 pages or the root of the site, but will add the class to the menu item if the current URL matches the menu item URL. 此方法将忽略404页或网站的根目录,但是如果当前URL与菜单项URL匹配,则将类添加到菜单项。

Full credit for this code: http://www.rarescosma.com/2010/11/add-a-class-to-wp_nav_menu-items-with-urls-included-in-the-current-url/ 此代码的完整信用: http : //www.rarescosma.com/2010/11/add-a-class-to-wp_nav_menu-items-with-urls-included-in-the-current-url/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM