如何使用 WordPress Walker 添加父级作为子菜单 <li> 项目?

问题描述 投票:0回答:1

目前,我正在尝试修改 Walker_Nav_Menu 类,以将父元素作为 li 项包含在其子菜单中两次。

这就是我正在努力实现的目标。我不确定是否应该修改

start_lvl
函数或
start_el
函数。

<ul class="menu">
<li>
  <a href="linktomenu">Level 0 item</a>
  <ul class="submenu">
    <li><a href="linktoparent">Show All Level 0 item </a></li>
    <li><a href="#0">Back to parent</a></li>
    <li><a href="linktomenu">Level 1 item</a></li>
    <li><a href="linktomenu">Level 1 item</a></li>
  </ul>
</li>

我是 Walker 的新手。你能帮我解决这个问题吗? 我搜索了之前的问题,但没有找到任何相关内容。

php wordpress menu wp-nav-walker
1个回答
0
投票

我自己一直在使用

start_el
start_lvl
等来解决这个问题,我通过输出元素中的简单字符串计数来实现它。

我创建了一个方法来添加带有父链接的代码

function add_link_to_parent_element(&$output, $parent_element_id, $depth)
{
    $parent_id = get_post_meta($parent_element_id, '_menu_item_object_id', true);
    $item_type = get_post_meta($parent_element_id, '_menu_item_type', true);

    if ($item_type == 'taxonomy') {
        $texonomy_type = get_post_meta($parent_element_id, '_menu_item_object', true);
        $parent = get_term($parent_id, $texonomy_type);
        $parent->guid = get_term_link($parent);
        $parent->post_title = $parent->name;
    } else {
        $parent = get_post($parent_id, 'object');
    }

    if (strpos($output, "data-parent='$parent_id'") !== false) $output .= '';
    else {
        $back = __('back', 'sage');
        $goto = __('Go to: ', 'sage');
        $output .= "<li class='title hide-desktop' data-parent='$parent_id' data-depth='$depth'><a href='#'><svg viewBox='0 0 10 14'><use xlink:href='#pixelarrow'></use></svg><span>$back</span></a></li>";
        @$output .= "<li class='parent-link hide-desktop'><a href='$parent->guid'>$goto $parent->post_title</a></li>";
    }
}

在开始的

start_el
方法中,我使用了PHP的
substr_count
函数来检查链接是否已添加到当前级别。

function start_el(&$output, $item, $depth=0, $args=array(), $id=0)
    {
        if ($depth > 0 && substr_count($output, 'title hide-desktop') != $depth){
            $this->add_link_to_parent_element($output,$item->menu_item_parent);
        }
// rest of the start_el method
© www.soinside.com 2019 - 2024. All rights reserved.