我正在WordPress中构建自定义导航菜单,我有2级深度;父项和直接子项子项。有些物品是叶子。
我希望所有父项都没有url,以便我可以添加JS下拉功能。
下面的代码成功构建了我想要的菜单,但是,我需要识别当前页面,以便添加一个方便的CSS类,如.current-page或.current-parent-page。另外,如果我在子页面或项目上,我还需要识别当前父项和当前项目;就像我使用wp_nav_menu一样。我目前的代码是:
<?php
global $post;
$the_post_ID = $post->ID;
/*global $wp_query;
$page_object = $wp_query->get_queried_object();
$page_id = $wp_query->get_queried_object_id();*/
if( ($locations =get_nav_menu_locations()) && isset($locations['primary']) ):
$primary_nav_menu = wp_get_nav_menu_object( $locations['primary'] );
$primary_nav_menu_items = wp_get_nav_menu_items( $primary_nav_menu->term_id, array( 'order' => 'DESC' ) ); ?>
<ul class="off-canvas-list site-menu-list">
<?php foreach( (array) $primary_nav_menu_items as $nav_item ):
/* get page id by using menu item object id */
$nav_item_id = get_post_meta( $nav_item->ID, '_menu_item_object_id', true );
/* set up a page object to retrieve page data */
$page = get_page( $nav_item_id );
$link = get_page_link( $nav_item_id );
if( ! $nav_item->menu_item_parent ) { /* this nav item has no parent */
/* try to retrieve its child nav items */
/* check function get_nav_menu_item_children() in functions.php */
$child_nav_items = array();
$child_nav_items = get_nav_menu_item_children( $nav_item->ID, $primary_nav_menu_items, false );
if( empty( $child_nav_items ) ): /* nav item has no children - it is a leaf; it has a link url */?>
<li class="????">
<a href="<?php echo esc_url( $link ); ?>"><?php echo $nav_item->title; //$page->page_title; ?></a>
</li>
<?php else: // nav item has children nav items - construct a sub menu ?>
<li class="has-submenu">
<?php /* on mobile, it becomes a label button - do not include its url */?>
<a href="#" class="ic-font"><?php echo $nav_item->title;//$page->post_title; ?></a>
<ul class="sub-menu">
<?php
foreach ( (array) $child_nav_items as $child_nav_item ):
// get page id from using menu item object id
$child_nav_item_id = get_post_meta( $child_nav_item->ID, '_menu_item_object_id', true );
// set up a page object to retrieve page data
$child_nav_page = get_page( $child_nav_item_id );
$child_nav_page_link = get_page_link( $child_nav_item_id );?>
<li class="???">
<a href="<?php echo esc_url( $child_nav_page_link ); ?>"><?php echo $child_nav_item->title; //$child_nav_page->post_title; ?></a>
</li>
<?php endforeach;?>
</ul>
</li>
<?php endif; ?>
<?php } /* this nav item has no parent */ ?>
<?php endforeach; /* loop through the primary_nav_menu_items */ ?>
</ul>
<?php endif; /* locations */ ?>
我尝试使用$nav_item->object_id
并将其与当前的帖子ID进行比较但不起作用。我也尝试了is_page($nav_item->object_id)
,但没有工作。
感谢您的帮助。