wordpress定制中英文双栏菜单

付费节点推荐


免费节点


节点使用教程


wp_nav_menu() 有一个参数 walker ,它可以用来挂载我们自己的函数,从而输入自定义的内容。今天,我们就是使用这个 walker 来输出菜单描述。

首先我们来设置菜单描述

在 外观>菜单 设置页面,点击右上角的 “显示选项”勾选“图像描述”:

20170129150425

 

然后展开某个菜单项,就可以看到“图像描述”,我们可以进行编辑和保存。

20170129150108

现在我们要做的就是在菜单中直接输出“图像描述”所填的内容。如下图所示:

20170129145911

在主题的functions.php 中添加下面的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
 * 添加输出菜单描述的 Walker 类
 * https://www.wpdaxue.com/wp_nav_menu-output-description.html
 */
class description_walker extends Walker_Nav_Menu
{
	function start_el(&$output, $item, $depth, $args)
	{
		global $wp_query;
		$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
 
		$class_names = $value = '';
 
		$classes = empty( $item->classes ) ? array() : (array) $item->classes;
 
		$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );
		$class_names = ' class="'. esc_attr( $class_names ) . '"';
 
		$output .= $indent . '<li id="menu-item-'. $item->ID . '"' . $value . $class_names .'>';
 
		$attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
		$attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : '';
		$attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
		$attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';
 
		$prepend = '<strong>';
		$append = '</strong>';
		$description  = ! empty( $item->description ) ? '<span>'.esc_attr( $item->description ).'</span>' : '';
 
		if($depth != 0)
		{
			$description = $append = $prepend = "";
		}
 
		$item_output = $args->before;
		$item_output .= '<a'. $attributes .'>';
		$item_output .= $args->link_before .$prepend.apply_filters( 'the_title', $item->title, $item->ID ).$append;
		$item_output .= $description.$args->link_after;
		$item_output .= '</a>';
		$item_output .= $args->after;
 
		$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
	}
}

在菜单函数 wp_nav_menu() 中调用这个 walker 类

1
2
3
4
5
6
7
8
9
<?php
wp_nav_menu( 
	array( 
		'theme_location' => 'primary', 
		'menu_class' => 'nav-menu', 
		'walker' => new description_walker() //注意前面要有 new
		) 
	); 
?>

菜单输出的html结构大致如下:

1
2
3
4
5
6
7
<li id="menu-item-23" class="menu-item menu-item-type-taxonomy menu-item-object-whcm_category">
<a href="http://localhost/wp_fangao/whcm_category/%e6%96%87%e5%8c%96%e4%bc%a0%e5%aa%92/">文化传媒</a><span>chuanmei</span>
</li>

未经允许不得转载:Bcoder资源网 » wordpress定制中英文双栏菜单

相关推荐

更多优质资源关注微信公众号: bcoder

bcoder
赞 (7)
分享到:更多 ()

评论 0

评论前必须登录!

登陆 注册