This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

WordPress anchor_walker - adding #anchor to top menu items

By: dejliglama on Oct 16th, 2013  |  syntax: PHP  |  size: 2.02 KB  |  views: 39  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. /*Changing the way the wp_nav_menu outputs links (adding an anchor link */
  2. class anchor_walker extends Walker_Nav_Menu
  3. {
  4.       function start_el(&$output, $item, $depth, $args)
  5.       {
  6.            global $wp_query;
  7.            $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
  8.  
  9.            $class_names = $value = '';
  10.  
  11.            $classes = empty( $item->classes ) ? array() : (array) $item->classes;
  12.  
  13.            $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );
  14.            $class_names = ' class="'. esc_attr( $class_names ) . '"';
  15.  
  16.            $output .= $indent . '<li id="menu-item-'. $item->ID . '"' . $value . $class_names .'>';
  17.  
  18.                    $title_anchor = strtolower(esc_attr(apply_filters( 'the_title', $item->title, $item->ID )));
  19.                    
  20.            $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
  21.            $attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : '';
  22.            $attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
  23.  
  24. /*Using the REL field in admin to send a no_anchor message if we need to do a normal link to a page on the top menu*/
  25.            if (($depth == 0) && (esc_attr( $item->xfn ) !='no_anchor'))
  26.            {
  27.                        $attributes .= ! empty( $item->url )        ? ' href="#'.$title_anchor.'"' : '';
  28.  
  29.            }else{
  30.                            $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';
  31.            }
  32.  
  33.  
  34.             $item_output = $args->before;
  35.             $item_output .= '<a'. $attributes .'>';
  36.             $item_output .= $args->link_before .$prepend.apply_filters( 'the_title', $item->title, $item->ID ).$append;
  37.             $item_output .= $args->link_after;
  38.             $item_output .= '</a>';
  39.             $item_output .= $args->after;
  40.  
  41.             $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
  42.             }
  43. }
clone this paste RAW Paste Data