wordpress 导航栏 调用

环境:wordpress6、twentytwentyone模板

一、wp-content/themes/twentytwentyone/functions.php  添加以下代码:

1、注册 (左边是别名,右边是名称。别名会用在导航栏的调用上,名称则显示在菜单后台页面上:外观->菜单)
register_nav_menus(
			array(
				'primary' => esc_html__( 'Primary menu', 'twentytwentyone' ),
				'footer'  => esc_html__( 'Secondary menu', 'twentytwentyone' ),
			)
		);



2、重写类
class Custom_Walker_Nav_Menu extends Walker_Nav_Menu {
    
//在子菜单项之前输出子菜单的起始标记
	function start_lvl(&$output, $depth = 0, $args = array()) {
		$indent = str_repeat("\t", $depth);
		$output .= "\n$indent<ul class=\"sub-menu\">\n";
	}

//在子菜单项之后输出子菜单的结束标记
	function end_lvl(&$output, $depth = 0, $args = array()) {
		$indent = str_repeat("\t", $depth);
		$output .= "$indent</ul>\n";
	}

//输出每个菜单项的起始标记和内容
	function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {
		$indent = ($depth) ? str_repeat("\t", $depth) : '';

		$output .= $indent . '<li';

		// 添加 "nav-current" 类到当前活动菜单项
		if (in_array('current-menu-item', $item->classes) || in_array('current-menu-parent', $item->classes)) {
			$output .= ' class="nav-current"';
		}


		$output .= '><a href="' . $item->url . '">' . $item->title . '</a>';
	}

//输出每个菜单项的结束标记
	function end_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {
		if ($args->walker->has_children) {
			$output .= '</ul>';
		}

		$output .= "</li>\n";
	}
}

二、导航栏调用

<nav class="nav-bar">
		<div class="nav-wrap">
			<?php
			echo wp_nav_menu(array(
                'menu' => 'mymenu',    //(1)注释
				'theme_location' => 'Primary menu', //(2)注释
				'menu_class' => 'nav',
				'container' => 'ul',
				'walker' => new Custom_Walker_Nav_Menu(),
			));
			?>
		</div>
	</nav>

(1)注释

(2)注释

三、

四、

在WordPress中,`wp_nav_menu()`是一个用于输出导航菜单的函数。它有两个参数与导航菜单相关:`menu`和`theme_location`。

1. `menu`参数:这个参数允许你指定一个具体的菜单名称或标识符作为参数值。你可以在WordPress后台的“外观 -> 菜单”页面创建和管理这些菜单。`menu`参数是可选的,如果不指定它,`wp_nav_menu()`函数将根据下一个参数(`theme_location`)来选择菜单。

2. `theme_location`参数:这个参数允许你指定一个注册的菜单位置或标识符作为参数值。菜单位置是在主题的`functions.php`文件中使用`register_nav_menus()`函数注册的。通过使用`theme_location`参数,你可以告诉`wp_nav_menu()`函数在指定位置找到并输出相应的菜单。如果你同时指定了`menu`和`theme_location`参数,`theme_location`参数将优先于`menu`参数。

总结:
- `menu`参数用于指定具体的菜单名称或标识符,需要在菜单管理页面创建和管理。
- `theme_location`参数用于指定注册的菜单位置或标识符,需要在主题的`functions.php`文件中注册。
- 如果同时指定了`menu`和`theme_location`参数,`theme_location`参数优先生效。

使用这两个参数,你可以根据需要在主题中输出不同的导航菜单。

参考网址:掌握 WordPress 导航菜单的 15 个最佳教程 - 知乎

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值