先介紹兩個全域變數
- global $menu < 主選單
- global $submenu < 子選單
自定義後台選單就靠這兩個變數,透過admin_menu這個hook把值print出來。
/* V123 DEV https://v123.tw */ function V123DEV_admin_menu_change() { global $menu; global $submenu; print_r($menu); print_r($submenu); } add_action( 'admin_menu', 'V123DEV_admin_menu_change');
$menu print 出來主選單資料結構大概長這樣
/* V123 DEV https://v123.tw */ Array ( [2] => Array ( [0] => 控制台 [1] => read [2] => index.php [3] => [4] => menu-top menu-top-first menu-icon-dashboard [5] => menu-dashboard [6] => dashicons-dashboard ) [4] => Array ( [0] => [1] => read [2] => separator1 [3] => [4] => wp-menu-separator ) [10] => Array ( [0] => 媒體 [1] => upload_files [2] => upload.php [3] => [4] => menu-top menu-icon-media [5] => menu-media [6] => dashicons-admin-media ) )
$submenu print 出來主選單資料結構大概長這樣
/* V123 DEV https://v123.tw */ Array ( [index.php] => Array ( [0] => Array ( [0] => 首頁 [1] => read [2] => index.php ) [10] => Array ( [0] => 更新 <span class='update-plugins count-0'><span class='update-count'>0</span></span> [1] => update_core [2] => update-core.php ) ) [upload.php] => Array ( [5] => Array ( [0] => 媒體庫 [1] => upload_files [2] => upload.php ) [10] => Array ( [0] => 新增檔案 [1] => upload_files [2] => media-new.php ) [15] => Array ( [0] => Media Categories [1] => manage_categories [2] => edit-tags.php?taxonomy=media_category&post_type=attachment ) ) [edit-comments.php] => Array ( [0] => Array ( [0] => 全部迴響 [1] => edit_posts [2] => edit-comments.php ) ) [edit.php] => Array ( [5] => Array ( [0] => 全部文章 [1] => edit_posts [2] => edit.php ) [10] => Array ( [0] => 新增文章 [1] => edit_posts [2] => post-new.php ) [15] => Array ( [0] => 分類 [1] => manage_categories [2] => edit-tags.php?taxonomy=category ) [16] => Array ( [0] => 標籤 [1] => manage_post_tags [2] => edit-tags.php?taxonomy=post_tag ) ) )
其實看到這結構,應該不難推敲每個參數的作用是什麼,以下簡單地進行一個修改,就可以把選單的標題改掉了。
/* V123 DEV https://v123.tw */ function wptutsplus_change_post_menu_label() { global $menu; global $submenu; $menu[5][0] = 'News'; $submenu['edit.php'][5][0] = 'News Items'; $submenu['edit.php'][10][0] = 'Add News Item'; } add_action( 'admin_menu', 'wptutsplus_change_post_menu_label' );
但有時我們可能會有不同角色的使用者,用index的方式修改其實不是很準確,所以下面我們用每個menu的slug來判斷要修改的選單,另外修改他的權限,這種做法無論是什麼角色的使用者,選單都會被套用。
/* V123 DEV https://v123.tw */ function V123DEV_admin_menu_change() { global $menu; global $submenu; // 修改選單的名稱及權限 foreach($menu as $k => $v){ if(isset($v[5])&&$v[5]=='toplevel_page_uam_user_group'){ $menu[$k][0]= '訂閱管理'; $menu[$k][1]= 'read'; } } // 新增一個子選單 if(isset($submenu['uam_user_group'])){ $submenu['uam_user_group'][] = array( 0 => 'Manage user user groups', 1 => 'read', 2 => 'uam_user_group', 3 => 'Manage user user groups', ); } } add_action( 'admin_menu', 'V123DEV_admin_menu_change');
這是一個快速修改選單的方法