內容簡介
這個外掛提供一個 API,讓網站開發人員能在預設的選單編輯器上增加自訂欄位。
初始化範例
<?php
add_action('init', 'menu_excerpt__add_menu_field');
function menu_excerpt__add_menu_field() {
if (!is_callable('bh_add_custom_menu_fields'))
return;
bh_add_custom_menu_fields(array(
'excerpt' => array(
'description' => '摘要',
'type' => 'textarea',
)));
}
?>
存取欄位
存取您所增加的欄位最簡單的方法是使用以下方式:
$menu = '選單名稱';
$posts = wp_get_nav_menu_items($menu);
foreach ($posts as $p) {
$myitem = get_post_meta($p->ID, '_menu_item_youritem', true);
// 將 $myitem 傳回字串,
// 可以直接使用 "echo"
}
如果您喜歡使用選單位置來獲取選單名稱,可以使用以下程式碼替換上述程式碼的第一行:
$locations = get_nav_menu_locations();
$menu = $locations['位置名稱'];
如果您喜歡交換選單,選單位置會很有用。
不幸的是,這些範例並不能使用 WordPress 內建的選單巡覽器。要使用它們,您需要建立一個自訂的 Walker_Nav_Menu 類別,使用以下程式碼來存取自訂欄位(非常簡化的範例,需要擴展完整的 walker 巨集功能,網上有自訂巡覽欄教學):
class mywalker extends Walker_Nav_Menu {
function start_el(&$output, $item, $depth, $args) {
echo $item->custom_field
}
}
重要的是,欄位存放在第二變數上,它的行為像是一個物件。custom_field 部分是您所命名的欄位名稱,橫線用底線取代(以允許名稱可用作存取器)。
注意
這個外掛並不會自己做什麼,它只提供一個 API。
外掛標籤
開發者團隊
原文外掛簡介
This plugin provides an API which allows the developer of a site to add custom fields on the default menu editor.
Example Initialisation
array(
'description' => 'Excerpt',
'type' => 'textarea',
)));
}
?>
Accessing the fields
The easiest way to access the field(s) you’ve added is to use something along the lines of:
$menu = 'menuName';
$posts = wp_get_nav_menu_items($menu);
foreach ($posts as $p) {
$myitem = get_post_meta($p->ID, '_menu_item_youritem', true);
// do with $myitem what you like - it should be a string,
// so the simplest thing is to "echo" it
}
you can use menu locations to get the menu name if you prefer – replace the first line above with:
$locations = get_nav_menu_locations();
$menu = $locations['locationName'];
menu locations are useful if you like to swap your menus about.
Unfortunately these examples don’t allow the use of wordpress’ inbuilt menu walkers. To use those you will need to create a custom walker_nav_menu class and access the custom fields with something along the lines of (very stripped down example will need fleshing out for full walker functionality – there are tutorials on the net for custom nav walkers):
class mywalker extends Walker_Nav_Menu {
function start_el(&$output, $item, $depth, $args) {
echo $item->custom_field
}
}
The important bit here is that the field is placed on the second variable which behaves like an object. the custom_field part is the name you gave your field with dashes replaced with underscores (to allow the name to be used in an accessor).
NOTE
This plugin does nothing by itself. It provides an API only.
