問題描述

我有一個需要兩個”main menus” 的客戶端,我們需要以程式設計方式顯示當前頁面中包含的任何選單。我怎樣才能做到這一點?

例如:我們在”About” 頁面。找出兩個選單中的哪一個包含”About” 頁面並顯示一個。

最佳解決方案

這是我寫的這個功能。您給它一個選單 slug /name /ID 和 post /page ID,如果該 post /page 在指定的選單中,並且 FALSE 則返回 TRUE 。那麼這只是一個快速 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 );
}

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。