Home » Hooks » wp_page_menu

Hook Name: wp_page_menu


The wp_page_menu hook allows developers to customize the output of the navigation menu generated by WordPress for the pages on a website. It is a filter hook that is triggered when the wp_page_menu() function is called.

By using the wp_page_menu hook, developers can modify the HTML markup, add or remove classes, change the structure, or even completely replace the default navigation menu with a custom one.

This hook is particularly useful when you want to enhance the user experience by adding additional functionality or styling to the page menu, such as adding dropdown menus, highlighting the current page, or applying custom CSS classes.

Example Usage:

Let’s say you want to add a CSS class to the navigation menu items for all the parent pages. You can achieve this by adding a callback function to the wp_page_menu hook.

function custom_nav_menu_classes($nav_menu, $args) {
    // Add a CSS class to parent menu items
    $nav_menu = str_replace('<li class="menu-item', '<li class="menu-item parent-item', $nav_menu);

    return $nav_menu;
add_filter('wp_page_menu', 'custom_nav_menu_classes', 10, 2);

In the example above, the custom_nav_menu_classes function takes two parameters: $nav_menu, which holds the generated navigation menu markup, and $args, which contains the arguments passed to the wp_page_menu() function.

Inside the function, we use the str_replace function to find all instances of <li class="menu-item and replace it with <li class="menu-item parent-item. This adds the "parent-item" class to the parent menu items.

Finally, we use the add_filter function to attach our callback function to the wp_page_menu hook. Now, whenever the wp_page_menu function is called, our function will be executed, allowing us to modify the navigation menu output as desired.

Remember, this is just one example of how you can leverage the wp_page_menu hook. The possibilities are endless, allowing you to customize and enhance the WordPress navigation menu to suit your specific needs.

Learn More on WordPress.org

WordPress snippets using the wp_page_menu hook

Register an account to save your snippets or go Pro to get more features.