wlanni

add current-menu-item to non-related wp_nav_menu

Jan 2nd, 2013
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.55 KB | None | 0 0
  1. // Need to add a class (using 'current-menu-item' to the nav menu to highlight it
  2. // when on custom post type pages (e.g. "/movies/" )
  3. // Calendar needs to look for "Calendar, Venues,
  4. // (and in this case Organizers, if you've updated the post_type with a slug)
  5. function add_parent_url_menu_class( $classes = array(), $item = false ) {
  6.     // Get current URL
  7.     $current_url = current_url();
  8.    
  9.     // Get homepage URL
  10.     $homepage_url = trailingslashit( get_bloginfo( 'url' ) );
  11.    
  12.     // Exclude 404 and homepage
  13.     if( is_404() or $item->url == $homepage_url ) return $classes;
  14.    
  15.     // if $item->url can be found in $current_url
  16.     // OR if $current_url (haystack) contains organizer, venue, events
  17.     // AND $item->url is blah/calendar, add class
  18.     if ( strstr( $current_url, $item->url) || ( ( strstr( $current_url, '/events/' ) || strstr ($current_url, '/organizer/') || strstr($current_url,'/venue/') )  && strstr( $item->url, '/calendar/') ) ) {
  19.         // Add the 'current-menu-item' class
  20.         $classes[] = 'current-menu-item';
  21.     }
  22.  
  23.     return $classes;
  24. }
  25. add_filter( 'nav_menu_css_class', 'add_parent_url_menu_class', 10, 2 );
  26.  
  27. // this is a helper function to the above add_parent_url_menu_class;
  28. // it checks the current url and pulls all the universal stuff out
  29. function current_url() {
  30.     // Protocol
  31.     $url = ( 'on' == $_SERVER['HTTPS'] ) ? 'https://' : 'http://';
  32.  
  33.     $url .= $_SERVER['SERVER_NAME'];
  34.  
  35.     // Port
  36.     $url .= ( '80' == $_SERVER['SERVER_PORT'] ) ? '' : ':' . $_SERVER['SERVER_PORT'];
  37.  
  38.     $url .= $_SERVER['REQUEST_URI'];
  39.  
  40.     return trailingslashit( $url );
  41. }
Advertisement
Add Comment
Please, Sign In to add comment