@Milo的代码是一个很好的基线,但我遇到了两个问题:
它依赖于外观下指定的菜单名称→ 菜单。如果此名称发生更改,还需要在主题文件中进行更新如果找不到匹配的菜单,您可能实际上并不需要消息;“找不到菜单”;用户的输出我已经更新了代码,并进行了以下改进:
添加了另一个助手函数,该函数根据提供的位置检索菜单名称。这将阻止我列出的第一个问题更改了;“找不到菜单”;消息是一个PHP警告,带有更详细的描述,重新格式化了代码以便于阅读,通过更详细的注释,更新了代码的一些方面(还根据我自己的喜好更改了一些内容)
在可能的情况下添加了类型转换功能添加了特定分隔符和类的功能返回值,而不是重复值(更容易进行条件检查)/**
* Retrieve a menu title from the database given the location the menu is assigned to
*
* @param string $location Menu location
*
* @return string The name of the menu
*/
function wpse324751_get_menu_title(string $location): string {
$menu_name = "";
$locations = get_nav_menu_locations();
if (isset($locations[$location]) && $menu = get_term($locations[$location], "nav_menu")) {
$menu_name = $menu->name;
}
return $menu_name;
}
/**
* Filter through an array of menu items to locate one specific item
*
* @param string $field
* @param integer $object_id
* @param array $items
* @return WP_Post|bool
*/
function wpse324751_get_menu_item(string $field, int $object_id, array $items) {
foreach ($items as $item) {
if (intval($item->$field) === $object_id) return $item;
}
return false;
}
/**
* Display breadcrumbs based on a given menu
*
* @param string $menu_location
* @param string $separator
* @param string $class
* @return string
*/
function wpse324751_nav_menu_breadcrumbs(string $menu_location, string $separator = "›", string $class = ""): string {
/**
* Locate all menu items of the provided menu
*/
$items = wp_get_nav_menu_items(wpse324751_get_menu_title($menu_location));
/**
* If no items exist, return empty
*/
if ($items === false) {
trigger_error("A menu at location \'" . sanitize_text_field($menu_location) . "\' could not be located.", E_USER_WARNING);
return "";
}
/**
* Locate the menu item for the viewed page
*/
$item = wpse324751_get_menu_item("object_id", get_queried_object_id(), $items);
/**
* If no viewed item could be located, return empty
*/
if ($item === false){
return "";
}
/**
* Store an array of items to construct the breadcrumb
*/
$menu_item_objects = [$item];
/**
* Locate all parents of the viewed item
*/
while (intval($item->menu_item_parent) !== 0) {
$item = wpse324751_get_menu_item("ID", $item->menu_item_parent, $items);
$menu_item_objects[] = $item;
}
/**
* Initialize array to store breadcrumbs
*/
$breadcrumbs = [];
/**
* Convert menu items to links and store them in the array
*/
foreach($menu_item_objects as $menu_item) {
$breadcrumbs[] = sprintf("<a class=\'text__link link\' href=\'%s\'>%s</a>", $menu_item->url, $menu_item->title);
}
/**
* Return the breadcrumbs
*/
return "<p class=\'" . esc_attr(trim("text {$class}")) . "\'>" . join(" {$separator} ", array_reverse($breadcrumbs)) . "</p>";
}