doufang2228 2014-04-29 21:09
浏览 43
已采纳

WordPress nav_menu - 按菜单名称过滤带条件语句的输出?

I'm using the Dynamic Menus within WordPress as a widget. I'm trying to filter the output so that I can add a class to the <a> tags (not the parent <li> as is default) without relying on jQuery.

I do not want to filter by theme_location since I am switching the menu depending on page and cannot assign multiple dynamic menus to one location.

I'd like to target these menus by Menu Name.

So far i've come close by realizing what the available arguments are for wp_nav_menu found in the response to this question : https://wordpress.stackexchange.com/questions/53950/add-a-custom-walkter-to-a-menu-created-in-a-widget

The following seems to be working fine:

add_filter('wp_nav_menu_items','replace_class', 10, 2);

function replace_class($items, $args) 
{
    if ($args->menu->term_id == '27') {
            $items = preg_replace('/<a/', '<a class="custom-class"', $items);
        }

    return $items;

}

However this is only by using the "term_id" for the menu.

Trying to do something like: if ($args->menu == 'menu-services') { for whatever reason does not work. Could I be using the wrong filter?

  • 写回答

1条回答 默认 最新

  • dongshan1959 2014-04-29 21:13
    关注

    *UPDATE*

    If you want to use your method or function - just add slug

    add_filter('wp_nav_menu_items','replace_class', 10, 2);
    
    function replace_class($items, $args) 
    {
        if ($args->menu->slug == 'your-menu-name') {
                $items = preg_replace('/<a/', '<a class="custom-class"', $items);
            }
    
        return $items;
    
    }
    

    Original Answer:

    I answered this yesterday - see my answer here

    Based on the link you provided (from wordpress stackexchange) add this code to add a custom walker to your widget menu:

    function widget($args, $instance) {
        // Get menu
        $nav_menu = ! empty( $instance['nav_menu'] ) ? wp_get_nav_menu_object( $instance['nav_menu'] ) : false;
    
        if ( !$nav_menu )
            return;
    
        $instance['title'] = apply_filters( 'widget_title', empty( $instance['title'] ) ? '' : $instance['title'], $instance, $this->id_base );
    
        echo $args['before_widget'];
    
        if ( !empty($instance['title']) )
            echo $args['before_title'] . $instance['title'] . $args['after_title'];
    
        wp_nav_menu( array( 'fallback_cb' => '', 'menu' => $nav_menu ) );
    
        echo $args['after_widget'];
    }
    $defaults = array( 'menu' => '', 'container' => 'div', 'container_class' => '', 'container_id' => '', 'menu_class' => 'menu', 'menu_id' => '',
    'echo' => true, 'fallback_cb' => 'wp_page_menu', 'before' => '', 'after' => '', 'link_before' => '', 'link_after' => '', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
    'depth' => 0, 'walker' => '', 'theme_location' => '' );
    
    $args = wp_parse_args( $args, $defaults );
    $args = apply_filters( 'wp_nav_menu_args', $args );
    $args = (object) $args;
    function myplugin_custom_walker( $args ) {
        return array_merge( $args, array(
            'walker' => new Class_Name_Walker(),
            // another setting go here ... 
        ) );
    }
    add_filter( 'wp_nav_menu_args', 'myplugin_custom_walker' );
    

    then add this walker - which adds the classes to the a

    class Class_Name_Walker extends Walker_Nav_Menu
        {
            /**
             * Start the element output.
             *
             * @param  string $output Passed by reference. Used to append additional content.
             * @param  object $item   Menu item data object.
             * @param  int $depth     Depth of menu item. May be used for padding.
             * @param  array $args    Additional strings.
             * @return void
             */
             function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
            $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
    
            $class_names = $value = '';
    
            $classes = empty( $item->classes ) ? array() : (array) $item->classes;
            $classes[] = 'menu-item-' . $item->ID;
    
            $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
            $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';
    
            $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
            $id = $id ? ' id="' . esc_attr( $id ) . '"' : '';
    
            $output .= $indent . '<li' . $id . $value .'>';
    
            $atts = array();
            $atts['title']  = ! empty( $item->attr_title ) ? $item->attr_title : '';
            $atts['target'] = ! empty( $item->target )     ? $item->target     : '';
            $atts['rel']    = ! empty( $item->xfn )        ? $item->xfn        : '';
            $atts['href']   = ! empty( $item->url )        ? $item->url        : '';
    
            $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args );
    
            $attributes = '';
            foreach ( $atts as $attr => $value ) {
                if ( ! empty( $value ) ) {
                    $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
                    $attributes .= ' ' . $attr . '="' . $value . '"';
                }
            }
            $item_output = $args->before;
            $item_output .= '<a'. $attributes .$class_names.'>';
            $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
            $item_output .= '</a>';
            $item_output .= $args->after;
    
            $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
        }
    
        /**
         * @see Walker::end_el()
         * @since 3.0.0
         *
         * @param string $output Passed by reference. Used to append additional content.
         * @param object $item Page data object. Not used.
         * @param int $depth Depth of page. Not Used.
         */
        function end_el( &$output, $item, $depth = 0, $args = array() ) {
            $output .= "</li>
    ";
        }
        }
    

    In your admin area go to Appearance > Menus. On the top right of the screen click on 'Screen Options' on the bottom row - make sure 'CSS Classes' is checked.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100