英文:
Custom Walker Show Top Level Item Name
问题
I am using the following custom NAV Walker to output a custom submenu. I would like to include the parent title in the walker but it's just showing up blank.
class Custom_Walker_Nav_Menu extends Walker_Nav_Menu {
function start_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat( "\t", $depth );
$parent_id = $this->db_fields['id'][ $depth - 1 ];
$parent_item = get_post( $parent_id );
$parent_title = $parent_item->post_title;
$output .= "\n$indent<p class=\"menu-title\">$parent_title</p>\n";
$output .= "\n$indent<ul class=\"sub-menu\">\n";
}
function end_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat( "\t", $depth );
$output .= "$indent</ul>\n";
}
}
wp_nav_menu( array(
'theme_location' => 'primary',
'menu_class' => 'nav-menu',
'depth' => 2,
'container' => 'div',
'container_class' => '',
'container_id' => 'main-navigation',
'walker' => new Custom_Walker_Nav_Menu(),
) );
英文:
I am using the following custom NAV Walker to output a custom submenu. I would like to include the parent title in the walker but it's just showing up blank.
class Custom_Walker_Nav_Menu extends Walker_Nav_Menu {
function start_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat( "\t", $depth );
$parent_id = $this->db_fields['id'][ $depth - 1 ];
$parent_item = get_post( $parent_id );
$parent_title = $parent_item->post_title;
$output .= "\n$indent<p class=\"menu-title\">$parent_title</p>\n";
$output .= "\n$indent<ul class=\"sub-menu\">\n";
}
function end_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat( "\t", $depth );
$output .= "$indent</ul>\n";
}
}
wp_nav_menu( array(
'theme_location' => 'primary',
'menu_class' => 'nav-menu',
'depth' => 2,
'container' => 'div',
'container_class' => '',
'container_id' => 'main-navigation',
'walker' => new Custom_Walker_Nav_Menup(),
) );
答案1
得分: 0
我决定使用 jQuery,在需要的地方包含父标题。当用户悬停在菜单项上时,我使用 jQuery 将文本复制到目标元素中。
$(document).ready(function () {
$('#main-navigation li.menu-item-has-children > a').hover(function () {
// 在悬停时,从源元素获取文本
var sourceText = $(this).text();
// 用源文本替换目标元素中的文本
$('.mega-menu .header-title').text(sourceText);
});
})
英文:
I decided to use jQuery to include the parent title where I needed it. When the user hovers over the menu item, I use jQuery to copy the text to the target element.
$(document).ready(function () {
$('#main-navigation li.menu-item-has-children > a').hover(function () {
// On hover, get text from source element
var sourceText = $(this).text();
// Replace text in target element with source text
$('.mega-menu .header-title').text(sourceText);
});
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论