我有一个客户想要两个“主菜单”,我们需要以编程方式显示包含当前页面的菜单。 我怎样才能做到这一点?
例如:我们在“关于”页面上。 找出两个菜单中的哪一个包含“关于”页面并显示该页面。
这是我为解决这个问题而编写的函数。 你给它一个 menu slug/name/ID 和 post/page ID 然后它返回 TRUE
如果该帖子/页面在指定的菜单中,并且 FALSE
否则。 然后只需一个快速的 if/else 语句来检查两个菜单并显示正确的菜单。
/**
* Check if post is in a menu
*
* @param $menu menu name, id, or slug
* @param $object_id int post object id of page
* @return bool true if object is in menu
*/
function cms_is_in_menu( $menu = null, $object_id = null ) {
// get menu object
$menu_object = wp_get_nav_menu_items( esc_attr( $menu ) );
// stop if there isn't a menu
if( ! $menu_object )
return false;
// get the object_id field out of the menu object
$menu_items = wp_list_pluck( $menu_object, 'object_id' );
// use the current post if object_id is not specified
if( !$object_id ) {
global $post;
$object_id = get_queried_object_id();
}
// test if the specified page is in the menu or not. return true or false.
return in_array( (int) $object_id, $menu_items );
}
用法示例:
if( cms_is_in_menu( 'main-menu' ) ) {
// do something like wp_nav_menu( $args );
}
