1
我做了一個功能,插入導航菜單到我的WordPress主題。我會喜歡你的建議,如何使它更好,也許更小。它是:php代碼優化的WordPress導航菜單
function cosmos_nav_menu($theme_location, $type) {
switch ($type) {
case 'basic-tabs' :
$menu_class = 'nav nav-tabs';
$wrap_before = '';
$wrap_after = '';
break;
case 'stacked-tabs' :
$menu_class = 'nav nav-tabs nav-stacked';
$wrap_before = '';
$wrap_after = '';
break;
case 'basic-pills' :
$menu_class = 'nav nav-pills';
$wrap_before = '';
$wrap_after = '';
break;
case 'stacked-pills' :
$menu_class = 'nav nav-pills nav-stacked';
$wrap_before = '';
$wrap_after = '';
break;
case 'list' :
$menu_class = 'nav nav-list';
$wrap_before = '';
$wrap_after = '';
break;
case 'navbar' :
$menu_class = 'nav';
$wrap_before = "<div class=\"navbar\">\n<div class=\"navbar-inner\">\n<div class=\"container\">\n";
$wrap_before .= "<a class=\"btn btn-navbar\" data-toggle=\"collapse\" data-target=\".nav-collapse\">\n";
$wrap_before .= "<span class=\"icon-bar\"></span>\n<span class=\"icon-bar\"></span>\n<span class=\"icon-bar\"></span>\n</a>\n";
$wrap_before .= "<div class=\"nav-collapse\">\n";
$wrap_after = "\n</div>\n</div>\n</div>\n</div>";
break;
case 'navbar-brand' :
$menu_class = 'nav';
$wrap_before = "<div class=\"navbar\">\n<div class=\"navbar-inner\">\n<div class=\"container\">\n";
$wrap_before .= "<a class=\"btn btn-navbar\" data-toggle=\"collapse\" data-target=\".nav-collapse\">\n";
$wrap_before .= "<span class=\"icon-bar\"></span>\n<span class=\"icon-bar\"></span>\n<span class=\"icon-bar\"></span>\n</a>\n";
$wrap_before .= "<a class=\"brand\" href=\"" . home_url('/') . "\">" . esc_html(get_bloginfo('name', 'display')) . "</a>\n";
$wrap_before .= "<div class=\"nav-collapse\">\n";
$wrap_after = "\n</div>\n</div>\n</div>\n</div>";
break;
}
echo $wrap_before;
wp_nav_menu(array(
'theme_location' => $theme_location,
'container' => false,
'menu_class' => $menu_class,
'walker' => new Bootstrap_Walker()
));
echo $wrap_after;
}
它基本上是wordpress'wp_nav_menu()函數的一個包裝。它在基於$ type變量調用wp_nav_menu()函數之前和之後添加了一些html代碼。前五個例子的前後代碼都沒有。在過去的兩種情況下,代碼重複也相當多。我還想包括一個情況,其中賦予$ type變量的字符串不匹配任何情況並根據回顯消息。
我最初用很多「if」語句代替「case」來編寫這個函數,但是他們中的任何一個對我都沒有好看。
任何幫助將不勝感激。