maxyudin

Add a class to nav menu items depending on URL

Feb 15th, 2013
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.94 KB | None | 0 0
  1. /*
  2. From:
  3. http://www.rarescosma.com/2010/11/add-a-class-to-wp_nav_menu-items-with-urls-included-in-the-current-url/
  4. */
  5.  
  6. add_filter( 'nav_menu_css_class', 'add_parent_url_menu_class', 10, 2 );
  7.  
  8. function add_parent_url_menu_class( $classes = array(), $item = false ) {
  9.     // Get current URL
  10.     $current_url = current_url();
  11.  
  12.     // Get homepage URL
  13.     $homepage_url = trailingslashit( get_bloginfo( 'url' ) );
  14.  
  15.     // Exclude 404 and homepage
  16.     if( is_404() or $item->url == $homepage_url ) return $classes;
  17.  
  18.     if ( strstr( $current_url, $item->url) ) {
  19.         // Add the 'parent_url' class
  20.         $classes[] = 'parent_url';
  21.     }
  22.  
  23.     return $classes;
  24. }
  25.  
  26. function current_url() {
  27.     // Protocol
  28.     $url = ( 'on' == $_SERVER['HTTPS'] ) ? 'https://' : 'http://';
  29.  
  30.     $url .= $_SERVER['SERVER_NAME'];
  31.  
  32.     // Port
  33.     $url .= ( '80' == $_SERVER['SERVER_PORT'] ) ? '' : ':' . $_SERVER['SERVER_PORT'];
  34.  
  35.     $url .= $_SERVER['REQUEST_URI'];
  36.  
  37.     return trailingslashit( $url );
  38. }
Advertisement
Add Comment
Please, Sign In to add comment