簡體   English   中英

如何獲得當前頁面菜單項祖先名稱wordpress

[英]How to get current page menu item ancestor name wordpress

我想知道如何檢索當前頁面的名稱作為變量。 例如,我的菜單如下:

Item 1
Item 2 => sub-item 1

項目1和2是自定義鏈接。 sub-item1是我的頁面。

當我在此頁面上時,我想檢索“項目2”的名稱(以構建我的自定義面包屑)

謝謝

面包屑:

這是一個與菜單層次結構一起使用的面包屑函數。 將此添加到主題的“ functions.php”中。

function my_menu_breadcrumb($theme_location, $separator = ' > ') {
    $locations = get_nav_menu_locations();
    if ( isset( $locations[ $theme_location ] ) ) {
        $menu = wp_get_nav_menu_object( $locations[ $theme_location ] );
        $menu_items = wp_get_nav_menu_items($menu->term_id);
        _wp_menu_item_classes_by_context( $menu_items );
        $breadcrumbs = array();

        foreach ( $menu_items as $menu_item ) {         
            if ($menu_item->current) {
                $breadcrumbs[] = "<span title=\"{$menu_item->title}\">{$menu_item->title}</span>";
            }
            else if ($menu_item->current_item_ancestor) {
                $breadcrumbs[] = "<a href=\"{$menu_item->url}\" title=\"{$menu_item->title}\">{$menu_item->title}</a>";
            }
        }

        echo implode($separator, $breadcrumbs);
     }
}

然后可以調用<?php my_menu_breadcrumb('header-menu'); ?> <?php my_menu_breadcrumb('header-menu'); ?>其中“ header-menu”是菜單位置名稱。 在循環中, $menu_item->title將返回頁面標題,而$menu_item->url是URL。

父菜單標題:

這是獲取當前頁面的父菜單項標題的函數-將其添加到主題的“ functions.php”中。

function my_menu_parent($theme_location) {
    $locations = get_nav_menu_locations();
    if ( isset( $locations[ $theme_location ] ) ) {
        $menu = wp_get_nav_menu_object( $locations[ $theme_location ] );
        $menu_items = wp_get_nav_menu_items($menu->term_id);
        _wp_menu_item_classes_by_context( $menu_items );
        $breadcrumbs = array();

        foreach ( $menu_items as $menu_item ) {         
            if ($menu_item->current_item_ancestor) {
                $breadcrumbs[] = $menu_item->title;
            }
        }

        return $breadcrumbs;
     }
}

然后,您可以如下調用,其中“ header-menu”是菜單位置名稱。

$parentitems = my_menu_parent( 'header-menu' );
foreach ( $parentitems as $parentitem ) {
    echo $parentitem."<br>";
}

您可以使用此

$pagename = get_query_var('pagename');  
if ( !$pagename && $id > 0 ) {  
// If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object  
$post = $wp_query->get_queried_object();  
$pagename = $post->post_name;  
}

在線上有很多教程和代碼片段,描述了如何在WordPress的子菜單中顯示活動頁面的子項(或在其中一個子項上,顯示活動頁面的兄弟姐妹)。 通常是這樣的:

<?php
$ref_post = empty($post->post_parent) ? $post->ID : $post->post_parent;
$children = wp_list_pages('title_li=&child_of='.$ref_post.'&echo=0');
if ($children) {
echo "<ul>$children</ul>";
}
?>

供參考:-https: //www.minddevelopmentanddesign.com/blog/showing-current-pages-parents-sub-menu-items-custom-nav-menu-wordpress/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM