【发布时间】:2019-01-25 06:45:47
【问题描述】:
我正在创建一个包含章节和子章节的页面,所有子章节都显示在章节页面上,而每个子章节都可以评论。为了更好地理解,我将描述结构:
我有以下页面结构:
- Chapter 1
- Chapter 2
- Chapter 3
对于每个章节,都有一个包含多个条目(帖子)的分层自定义帖子类型“sub_chapters”:
- Subchapter 1
- Subchapter 1.1
- Subchapter 1.2
- Subchapter 2
- Subchapter 3
第 1 章页面类似于概览页面,并从所有子章节获取内容。像这样:
Chapter 1 Title
- Subchapter 1 Content
- Subchapter 1 Comments
- Subchapter 1.1 Content
- Subchapter 1.1 Comments
- Subchapter 1.2 Content
- Subchapter 1.2 Comments
- Subchapter 2 Content
- Subchapter 2 Comments
- Subchapter 3 Content
- Subchapter 2 Comments
到目前为止一切正常,但现在我想将这些子章节自动附加到带有锚链接的 wordpress 菜单中。
自动追加
在我的模板中,每个子章节都有一个 id,它是从这个条目的 slug 构建的。 (例如id="subchapter-1-introduction")
我的 wp_nav_menu 仅包含 3 个页面:
- Chapter 1
- Chapter 2
- Chapter 3
我想创建一个菜单链接(括号中的网址):
- Chapter 1 (/chapter1/)
- Subchapter 1 Introduction (/chapter1/#subchapter1-introduction)
- Subchapter 1.1 (/chapter1/#subchapter1-1)
- Subchapter 2 (/chapter1/#subchapter2)
- Subchapter 3 (/chapter1/#subchapter3)
- Chapter 2 (/chapter1/)
...
- Chapter 3 (/chapter1/)
现在我尝试使用过滤器wp_get_nav_menu_items 构建此结构并更改 WP 导航菜单结构。但我只能在页面下方构建 1 级。我无法构建层次结构。
没有自动附加
所以我想好吧,我们不希望自动菜单附加,最好使用自定义walker。因为我还需要像current-menu-item 这样的wordpress 菜单类。
我在 Wordpress 后端菜单部分添加了 page/cpt 结构。这给了我一个不错的菜单,但是现在永久链接不像锚标签那样工作(如上所述)
我试图像这样改变 Walker_Nav_Menu 中的 start_el 函数:
if ( $depth > 0) {
// create link to page with anchor
$atts['href'] = $permalinkFromParentPage . '/#' $slugFromSubChapter .
} else {
// were on level 0, only the page link
$atts['href'] = ! empty( $item->url ) ? $item->url : '';
}
但在这种情况下,我不知道要获取 $permalinkFromParentPage,因为在 start_el 我只有有关实际菜单项的信息。
我该如何解决这个问题,或者有更好的解决方案吗?我知道我可以使用自定义链接,但是子章节太多,所以我更喜欢附加 wordpress 菜单类的“自动”菜单。
【问题讨论】: