search
HomeBackend DevelopmentPHP TutorialAnalysis function: inspection of wp_nav_menu

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 ); ?>

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'
);

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'
);

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></section> or <nav></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.

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'
);

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);

沃克级

现在我们准备使用 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 );
	}
}

这里发生了很多事情。有关 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;
}

这将更改每个链接的高度和填充,导致 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');
}

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!

Statement
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
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor