wordpress获取自定义菜单名称和链接(wp_nav_menu)

2017年2月22日原创教程 建站历程评论14,4685

最近接了一个活,做一个主题。其中有用到 <?php wp_nav_menu(); ?>来互获取自定义菜单的内容。文章源自狐狸影视城-https://fox-studio.net/32513.html

问题是总是无法获得,只有 <a href="">…</a> 这样的输出格式。最后研究了下,得到了想要的结果。文章源自狐狸影视城-https://fox-studio.net/32513.html

先看下<?php wp_nav_menu(); ?>的官方介绍文章源自狐狸影视城-https://fox-studio.net/32513.html

<?php
$parameter = array(
	'theme_location'  => '',				//指定显示的导航名,如果没有设置,则显示第一个
	'menu'            => 'header-menu',		
	'container'       => 'nav',				//最外层容器标签名
	'container_class' => 'primary',			//最外层容器class名
	'container_id'    => '',				//最外层容器id值
	'menu_class'      => 'sf-menu',			//ul标签class
	'menu_id'         => 'topnav',			//ul标签id
	'echo'            => true,				//是否打印,默认是true,如果想将导航的代码作为赋值使用,可设置为false
	'fallback_cb'     => 'wp_page_menu',	//备用的导航菜单函数,用于没有在后台设置导航时调用
	'before'          => '',				//显示在导航a标签之前
	'after'           => '',				//显示在导航a标签之后
	'link_before'     => '',				//显示在导航链接名之后
	'link_after'      => '',				//显示在导航链接名之前
	'items_wrap'      => '<ul id="%1$s">%3$s</ul>',
	'depth'           => 0,					//显示的菜单层数,默认0,0是显示所有层
	'walker'          => ''					//调用一个对象定义显示导航菜单
);
	
wp_nav_menu($parameter);

wordpress 中的自定义菜单函数 wp_nav_menu() 默认输出格式为:文章源自狐狸影视城-https://fox-studio.net/32513.html

<div>
	<ul>
		<li><a>菜单文字</a></li>
	</ul>
</div>

百度了一圈还真没几个,可以完全解决的。有人这样做文章源自狐狸影视城-https://fox-studio.net/32513.html

<?php
$parameter = array(
	'container' => 'false',
	'items_wrap' => '%3$s',
);
	
wp_nav_menu($parameter);

发现 <li> 标签还是无法去除。但是考虑下,如果加上文章源自狐狸影视城-https://fox-studio.net/32513.html

'echo' => false

输出带 <li> 的字符串,然后在用 strip_tags() 剥去其他标签,只保留 <a> 标签中的内容。就可以了。所以得到的完整代码如下。文章源自狐狸影视城-https://fox-studio.net/32513.html

 <?php 
$menuParameters = array(
	'container'	=> false,
	'echo'	=> false,
	'items_wrap' => '%3$s',
	'depth'	=> 0,
);
echo strip_tags(wp_nav_menu( $menuParameters ), '<a>' );

输出结果如下图:文章源自狐狸影视城-https://fox-studio.net/32513.html

wordpress获取自定义菜单名称和链接(wp_nav_menu)文章源自狐狸影视城-https://fox-studio.net/32513.html

wordpress获取自定义菜单名称和链接(wp_nav_menu)文章源自狐狸影视城-https://fox-studio.net/32513.html

weinxin
千年骚狐
  • 本文由 发表于 2017年2月22日
  • 除非特殊声明,本站文章均为原创,转载请务必保留本文链接
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定