問題描述

我正在嘗試使用 wp_nav_menu 只顯示菜單 (如果存在),否則不顯示任何內容。

如果我刪除菜單,它將輸出頁面列表。

我的 functions.php 文件包含:

if (function_exists('register_nav_menus')) {
register_nav_menus (
array('main_nav' => 'Main Navigation Menu'));}

如何使用 wp_nav_menu 才能顯示菜單,否則不顯示?

最佳解決方案

使用 has_nav_menu(),並測試 theme_location,而不是 menu_id

<?php
if ( has_nav_menu( $theme_location ) ) {
    // User has assigned menu to this location;
    // output it
    wp_nav_menu( array( 
        'theme_location' => $theme_location, 
        'menu_class' => 'nav', 
        'container' => '' 
    ) );
}
?>

您可以通過添加 else 子句來輸出備用內容。

編輯

您需要用 theme_location 替換 $theme_location

<?php
if ( has_nav_menu( 'main_nav' ) ) {
    // User has assigned menu to this location;
    // output it
    wp_nav_menu( array( 
        'theme_location' => 'main_nav', 
        'menu_class' => 'nav', 
        'container' => '' 
    ) );
}
?>

次佳解決方案

您可以將 wp_nav_menufallback_cb 參數指定為 false 。沒有什麼會出現 – 而是 wp_nav_menu 將返回 false(沒有回應) 。

<?php
wp_nav_menu(array( 
    'theme_location' => $main_nav, 
    'menu_class'     => 'nav', 
    'container'      => '',
    'fallback_cb'    => false
));

參考文獻

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