Home > Backend Development > PHP Tutorial > Analysis function: inspection of wp_nav_menu

Analysis function: inspection of wp_nav_menu

WBOY
Release: 2023-09-02 21:34:01
Original
1172 people have browsed it

When WordPress 3 gave us new menu features, it forever changed the way we view navigation menus. We no longer have to use the normal page list functionality or build our own custom menu functionality to integrate category and page menus as well as external or hard link items in the navigation menu. But how can we take advantage of this new feature for customization? In this tutorial, we'll dive into everything the wp_nav_menu function can do, add subdescriptions using the Walker class, and touch on some of its related functions.


parameter

This function has multiple parameters available. The following are the default values ​​listed in the WordPress.org Codex:

<?php $defaults = array(
	'theme_location'  => ,
	'menu'            => ,
	'container'       => 'div',
	'container_class' => 'menu-{menu slug}-container',
	'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'          =>
);
?>

<?php wp_nav_menu( $defaults ); ?>
Copy after login

Topic location

Using this parameter we can set the theme position and then use that position on the Menu page to set the menu that works in that part of the theme without having to manually define the menu that should be displayed here. This is very helpful for theme distributors because you can use conditions to display a menu only if the user has defined the menu for that location. The only other requirement is that you use the function register_nav_menu() to register these locations. When you set up menu support, this is usually done through function files.

Let's start building the custom menu function parameters, assuming we have registered a theme location named "primary".

$params = array(
	'theme_location' => 'primary'
);
Copy after login

menu

This parameter is used to manually define which menu should be used. In our example we are only setting a common menu location rather than defining the exact menu location to use, but if we wanted to tell the function to use a menu called "Main Navigation" our parameters would look like this:

$params = array(
	'theme_location' => 'primary',
	'menu' => 'Primary Navigation'
);
Copy after login

container

By default our menu will be contained within a div, but if you're like me, you don't usually need this and may want to reduce the number of divs and other tags Use volume to keep your code as clean as possible. You can also use this parameter to define different tags, such as html5 <section> or <nav>. For our example, we don't want the container to change the default container value because the twenty-one theme style relies on its existence.

Container class and container ID

As you can almost guess, these parameters are used to set the class and ID of the container. Since we're completely ignoring this, we don't need to define the value.

Menu class and menu ID

These work similarly to the previous parameters, except this time we're definitely going to set the ID of "nav" since that's the ID we'll use in our stylesheet to style the navbar.

$params = array(
	'theme_location' => 'primary',
	'container' => false,
	'menu_id' => 'nav'
);
Copy after login

echo

You can use this parameter to decide whether you want to display (echo) the result, or return it for use in PHP. The item is a boolean, so to return it, just set this parameter to 0.

Backup CB

This is a callback function, you can fall back to this function if the menu is not found. By default it uses the old support wp_page_menu() and passes all the same arguments to the function.

before and after

These items are used to define what can be placed before and after the anchor tag (<a></a>). You can use them to add a vertical bar before each item, or wrap navigation items in span tags.

Before linking and after linking

They work the same as the items we covered previously, except that anything you define will be inside the anchor tag. Our example does not require us to use these, so we will ignore them and leave the default empty project.

Item package

By default, items are contained in an unordered list with a menu ID and menu class. If you wish, you can change this via this parameter.

depth

This parameter is useful when you want to use the same menu twice but don't want any subitems to appear at the location you set using the wp_nav_menu() function. For example, if you want the main navigation to include a secondary drop-down menu, you can leave it as default. Then, if you want to use the same parent and omit the children in the footer navigation, you can set this parameter to depth 1. The default "0" means all levels will be output. To keep the example simple, let's assume that the main navigation does not contain any subitems.

Walker

This parameter is used to define a walker object, which can be used to manipulate how the entire function works and output its information. We'll discuss a good example in the next section.


Add descriptions to navigation menu items

For our example, we want to add a sub-description to each main menu item. The ability to add a description itself is already available in the WordPress menu system. To turn on this feature, go to the menu and press the Screen Options tab in the upper right corner. You need to make sure that the option clicked should be "Description". With this option selected, the menu items should now look like this:

Analysis function: inspection of wp_nav_menu

填写完描述后,我们需要创建 walker 类并将其添加到 wp_nav_menu() 参数中。我们将调用该类 description_navigation 因此我们完整的参数代码应如下所示:

$params = array(
	'theme_location' => 'primary',
	'menu_id' => 'nav',
	'walker' => new description_walker()
);
wp_nav_menu($params);
Copy after login

沃克级

现在我们准备使用 Walker 类添加这些描述:

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        ) .'"' : '';
		$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 .apply_filters( 'the_title', $item->title, $item->ID );
		$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 );
	}
}
Copy after login

这里发生了很多事情。有关 Walker 类的更多信息,请参阅另一个教程:了解 Walker 类。您在这里应该理解的最重要的部分是我们正在重建每个链接项的输出并添加描述。在上面代码片段的第 19 行,您可以看到我们在哪里获取项目描述(如果存在),并将其设置为包含在 span 标记中的 $description 的值,以便我们可以单独设置描述的样式。然后,在第 24-29 行中,我们将链接项重新组合在一起,在锚标记结束之前添加描述,以便它成为链接本身的一部分。

使用“二十一十一”主题,您现在应该拥有如下所示的内容:

Analysis function: inspection of wp_nav_menu

风格化

让我们添加一些样式以使其更清晰:

#nav a {
	line-height: 20px;
	padding: 10px 15px;
}

#nav a span {
	display: block;
	font-size: 11px;
	color: #ccc;
}

#nav a:hover span {
	color: #999;
}
Copy after login

这将更改每个链接的高度和填充,导致 span 标记内的描述下降到自己的行,并稍微调整字体大小和颜色以获得如下所示的最终结果:

Analysis function: inspection of wp_nav_menu


关系函数

您不仅可以使用 wp_nav_menu() 输出包含所有自定义内容的菜单,您还可以进一步使用其一些相关功能。

has_nav_menu()

此功能非常适合仅显示特定菜单(如果该菜单已分配给您的主题位置)。例如,您可能希望在主题上为用户可能不希望出现在主导航中的较少导航项创建顶部导航。这可能是主页链接、“与我们一起做广告”或其他较低级别的号召性用语。但作为主题分发者,如果您不知道这是否是用户想要使用的内容,只需使用如下条件:

if (has_nav_menu('top-menu')) {
	wp_nav_menu('theme_location='top-menu');
}
Copy after login

wp_get_nav_menu_items()

此函数将从特定菜单返回项目数组。如果您想在不使用 Walker 类的情况下构建自定义菜单列表,这可能特别有用。您会失去很多功能,例如菜单项的当前类,但这是循环遍历菜单项数组以获得简单解决方案的好方法。


结论

当您更多地了解内置参数提供的灵活性并能够通过 Walker Class 进行更好的控制时,您可以做很多事情来自定义导航菜单。需要为每个项目添加另一个带有“icon”类的span标签来自定义图标吗?没问题。

能够完全控制菜单的放置和输出,可以扩展您作为主题开发人员的能力,带来不可估量的可能性。您可以使用 Walker 类来做哪些事情?

The above is the detailed content of Analysis function: inspection of wp_nav_menu. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template