問題描述
我是 WordPress 的新手,我仍然試圖從這個眾所周知的 CMS 中學到內在和外在的東西。
我想知道,如果我應該或必須有主選單的回退?
這是我正在使用的:
// This theme uses wp_nav_menu() in one location.
register_nav_menus( array(
'primary' => __( 'Primary Navigation', 'xxxxxx' ),
) );
這裡是我的 header.php 檔案中的回撥:
<nav>
<?php wp_nav_menu(
array(
'theme_location' => 'Primary',
'menu' => 'Primary',
'container' => '',
'items_wrap' => '<ul class="main">%3$s</ul>'
));
?>
</nav>
就像我說的,我是新的。所以請任何幫助將是非常歡迎的。
如果可以的話,請回應一個例子。
最佳解決辦法
當使用者沒有將選單分配給 theme_location 時,將使用引數 fallback_cb 。它應該是一個返回一個字串的函式,但是可以使用__return_false()來抑制任何輸出:
wp_nav_menu(
array(
'theme_location' => 'primary',
// No menu available: no output.
'fallback_cb' => '__return_false'
)
);
您應該始終明確地宣告回退,以保持程式碼的可讀性。
以 TwentyEleven 為例:
<?php
/* Our navigation menu. If one isn't filled out, wp_nav_menu
falls back to wp_page_menu. The menu assigned to the primary
location is the one used. If one isn't assigned, the menu with
the lowest ID is used. */
?>
<?php wp_nav_menu( array( 'theme_location' => 'primary' ) ); ?>
這很混亂人們可以認為,如果沒有分配給這個主題位置的選單,主題現在將使用第一個可用的自定義選單。錯誤。將使用頁面列表。宣告回撥會更容易理解。
回退將獲得所有選單引數。您必須檢查 echo 引數,因為 WordPress 不會為您照顧。並確保尊重其他引數,以獲得正確樣式的輸出。
一個高階示例:如果沒有分配給主題位置的選單,則返回任何內容 – 如果當前使用者可以實際建立選單,則返回到選單編輯器的連結:
/**
* Menu fallback. Link to the menu editor if that is useful.
*
* @param array $args
* @return string
*/
function link_to_menu_editor( $args )
{
if ( ! current_user_can( 'manage_options' ) )
{
return;
}
// see wp-includes/nav-menu-template.php for available arguments
extract( $args );
$link = $link_before
. '<a href="'%20.admin_url(%20'nav-menus.php'%20)%20.%20'">' . $before . 'Add a menu' . $after . '</a>'
. $link_after;
// We have a list
if ( FALSE !== stripos( $items_wrap, '<ul' )
or FALSE !== stripos( $items_wrap, '<ol' )
)
{
$link = "<li>$link</li>";
}
$output = sprintf( $items_wrap, $menu_id, $menu_class, $link );
if ( ! empty ( $container ) )
{
$output = "<$container class='$container_class' id='$container_id'>$output</$container>";
}
if ( $echo )
{
echo $output;
}
return $output;
}
現在我們可以這樣呼叫這個選單
$menu = wp_nav_menu(
array(
'theme_location' => 'primary',
'fallback_cb' => 'link_to_menu_editor',
'echo' => FALSE
)
);
echo $menu;
… 和管理員將在主題的樣式表期望的所有標記中獲得有用的連結:
一般的訪客將無所事事。
次佳解決辦法
見食典中的 wp_nav_menu()
wp_nav_menu 的預設 fall-back(fallback_cb 引數) 為'wp_page_menu',因此如果不分配主選單,我認為您應該 auto-magically 有一個頁面選單 (每個靜態頁面的選單,只有靜態頁面) 。
不是這樣嗎?
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。
