从其 ID 获取菜单项标题



我需要获取顶级导航的标题。我已经知道顶级菜单项的 ID,但我需要获取它的标题。怎么能做到这一点呢?

我目前有这样的菜单:

  • 级别 1
    • 级别 2 #1
    • 级别 2 #2
    • 级别2 #3

如果我在任何 2 级页面上,我有 1 级菜单项ID。我需要在当前主题位置实例中获取标题。

<?php if(getTopSelectedMenu('primary')):
$topParent = intval(getTopSelectedMenu('primary'));
$topParentTitle = "";
?>
<div class="sidebar-menu-headline"><?=$topParentTitle?><i class="fa fa-arrow-down" aria-hidden="true"></i></div>
<?php
$args = array(
'menu' => '',
'menu_class' => 'sidebar-menu',
'container' => 'ul',
'theme_location' => 'primary',
'level' => 2,
'child_of' => $topParent,
'echo' => FALSE,
'fallback_cb' => '__return_false'
);
$submenu = wp_nav_menu( $args );
if ( ! empty ($submenu) )echo $submenu;
?>

使用以下函数通过传递菜单 ID 来获取菜单标题。

Function: wp_get_nav_menu_object($menu) // $menu can be 'id','name' or 'slug'
Returns : Object (
term_id => 4
name => My Menu Name
slug => my-menu-name
term_group => 0
term_taxonomy_id => 4
taxonomy => nav_menu
description => 
parent => 0
count => 6
)
// in your case.
$menu = wp_get_nav_menu_object($topParent );
$menu_title = $menu->name;

您可以在此处找到更多信息。 https://codex.wordpress.org/Function_Reference/wp_get_nav_menu_object

若要获取菜单标题,请使用以下代码

if(getTopSelectedMenu('primary')){
$topParentId = intval(getTopSelectedMenu('primary'));
$menuLocations = get_nav_menu_locations(); // Get our nav locations (set in our theme, usually functions.php)
// This returns an array of menu locations ([LOCATION_NAME] = MENU_ID);
$menu =  wp_get_nav_menu_object($menuLocations['primary']) ; // Get the *primary* menu object
$primaryNav = wp_get_nav_menu_items($menu->term_id); // Get the array of wp objects, the nav items for our queried location.
foreach ( $primaryNav as $navItem ) {
if ($navItem->ID == $topParentId ) {
$topParentTitle = $navItem->title;
}
}
}
<div class="sidebar-menu-headline"><?=$topParentTitle?><i class="fa fa-arrow-down" aria-hidden="true"></i></div>

对,你想要简单!我抓住你了。

如果您知道 URL,请使用url_to_postid()

$actual_id = url_to_postid($url);
$the_title = get_the_title($actual_id);

或者简单地:

$the_title = get_the_title(url_to_postid($url));

真的没有遇到过这不准确的时候!

最新更新