This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.
WordPress hooks are super handy, right? They let you tweak and modify your site without touching the core files. Today, we’re diving into the page_menu_link_attributes filter. It does exactly what it sounds like—filters the HTML attributes applied to a page menu item’s anchor element. Let’s explore how you can use this filter in your WordPress site with some live examples.
Example 1: Basic Usage
Here’s a simple example of how you can use the page_menu_link_attributes filter. This example demonstrates how to modify the attributes of a menu link.
function weplugins_modify_page_menu_link_attributes_defaults($atts, $page, $depth, $args, $current_page_id) { // Update the $atts variable according to your website requirements and return this variable. You can modify the $atts variable conditionally too if you want. return $atts; } // add the filter add_filter("page_menu_link_attributes", "weplugins_modify_page_menu_link_attributes_defaults", 10, 5);
Example 2: Removing a Hook
Sometimes, you might need to remove a registered hook. You can easily do this using remove_filter. Here’s how you can remove the page_menu_link_attributes filter.
remove_filter("page_menu_link_attributes", "weplugins_modify_page_menu_link_attributes_defaults", 10, 5);
Please make sure to provide the same callback function name, priority, and number of arguments while removing the hook callback.
Example 3: Customizing Menu Attributes
In this example, learn how to customize the menu attributes based on certain conditions like the page ID or depth.
function weplugins_customize_menu_attributes($atts, $page, $depth, $args, $current_page_id) { if ($current_page_id == $page->ID) { $atts['class'] .= ' current-menu-item'; } return $atts; } add_filter("page_menu_link_attributes", "weplugins_customize_menu_attributes", 10, 5);
Below are the 5 parameters required to use this hook:
- $atts : (array) The HTML attributes applied to the menu item’s element, empty strings are ignored.
- $page : (WP_Post) Page data object.
- $depth : (int) Depth of page, used for padding.
- $args : (array) An array of arguments.
- $current_page_id : (int) ID of the current page.
Contact Us
If you’re having any trouble using this hook or need some customization, feel free to Contact Us. Our team at WePlugins is here to help!
Explore the latest in WordPress
Trying to stay on top of it all? Get the best tools, resources and inspiration sent to your inbox every Wednesday.