Question
Answer and Explanation
The add_menu_page()
function in WordPress doesn't directly support adding a custom class to the menu item that is generated. However, you can achieve the desired result by using a combination of hooks and filters. Here's how you can add a class to the menu item created by add_menu_page()
:
1. Understanding the Limitation:
- The add_menu_page()
function in WordPress primarily focuses on generating the menu structure. It doesn't provide a parameter to add HTML attributes like CSS classes directly. We need to use hooks to modify the output.
2. Using the `admin_menu` Hook:
- Start by using the admin_menu
hook to register your menu item using add_menu_page()
, as you usually would.
3. Using the `admin_head` Hook
- We can use javascript within the admin_head
hook to find the menu item generated by WordPress and modify it.
4. Example Code:
add_action('admin_menu', 'my_custom_menu_page');
function my_custom_menu_page() {
add_menu_page(
'My Custom Page', // Page title
'My Custom Menu', // Menu title
'manage_options', // Capability required
'my-custom-page', // Menu slug
'my_custom_page_content', // Callback function
'dashicons-admin-generic', // Icon
6 // Position
);
}
function my_custom_page_content() {
echo '<h2>My Custom Page Content</h2>';
}
add_action('admin_head', 'add_custom_class_to_menu');
function add_custom_class_to_menu() {
echo '<script type="text/javascript">';
echo 'document.addEventListener("DOMContentLoaded", function() {';
echo ' var menuItems = document.querySelectorAll("#adminmenu > li > a");';
echo ' menuItems.forEach(function(menuItem) {';
echo ' if(menuItem.getAttribute("href") === "admin.php?page=my-custom-page") {';
echo ' menuItem.parentElement.classList.add("my-custom-class");';
echo ' }';
echo ' });';
echo '});';
echo '</script>';
}
5. Explanation:
- The my_custom_menu_page()
function uses add_menu_page()
to create the new admin menu item.
- The add_custom_class_to_menu()
function adds a javascript to the admin page head. This script adds a class my-custom-class
to the parent element of the menu item with href="admin.php?page=my-custom-page"
6. Important Notes:
- Replace my-custom-page
with your actual menu slug and my-custom-class
with the class you want to add.
- Always use a unique slug for your menu pages and classes to avoid conflicts.
- This code runs on every admin page load, which is fine for this purpose. However if you plan to add more complex functionality you should optimize it
By using this approach, you can successfully add a custom class to the menu item created by add_menu_page()
in WordPress, allowing you to further customize the appearance of your menu items with CSS.