从其ID

时间:2017-08-28 18:37:57

标签: php wordpress

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

我目前有这样的菜单:

  • 级别1
    • Level2#1
    • Level2#2
    • Level2#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;

    ?>

2 个答案:

答案 0 :(得分:2)

使用以下功能通过传递菜单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>

答案 1 :(得分:0)

对,您要简单!我明白了。

如果您知道该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));

这真的不是一个不准确的时期!

相关问题