The page_menu_link_attributes WordPress PHP filter allows you to modify the HTML attributes applied to a page menu item’s anchor element.
Usage
add_filter( 'page_menu_link_attributes', 'my_custom_menu_link_attributes', 10, 5 ); function my_custom_menu_link_attributes( $atts, $page, $depth, $args, $current_page_id ) { // your custom code here return $atts; }
Parameters
$atts
(array): The HTML attributes applied to the menu item’s<a>
element, empty strings are ignored.href
(string): The href attribute.aria-current
(string): The aria-current attribute.
$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.
More information
See WordPress Developer Resources: page_menu_link_attributes
Examples
Add a CSS class to the menu link
Add a custom CSS class to the menu link based on the page ID.
add_filter( 'page_menu_link_attributes', 'add_custom_class_to_menu_link', 10, 5 ); function add_custom_class_to_menu_link( $atts, $page, $depth, $args, $current_page_id ) { $atts['class'] = 'custom-class-' . $page->ID; return $atts; }
Add a data attribute to the menu link
Add a custom data attribute to the menu link.
add_filter( 'page_menu_link_attributes', 'add_custom_data_attribute_to_menu_link', 10, 5 ); function add_custom_data_attribute_to_menu_link( $atts, $page, $depth, $args, $current_page_id ) { $atts['data-page-id'] = $page->ID; return $atts; }
Add a target attribute to the menu link
Open external links in a new tab.
add_filter( 'page_menu_link_attributes', 'open_external_links_in_new_tab', 10, 5 ); function open_external_links_in_new_tab( $atts, $page, $depth, $args, $current_page_id ) { if ( strpos( $atts['href'], site_url() ) === false ) { $atts['target'] = '_blank'; } return $atts; }
Make current menu item not clickable
Disable the current menu item link.
add_filter( 'page_menu_link_attributes', 'disable_current_menu_item_link', 10, 5 ); function disable_current_menu_item_link( $atts, $page, $depth, $args, $current_page_id ) { if ( $page->ID == $current_page_id ) { $atts['href'] = '#'; } return $atts; }
Add a title attribute to the menu link
Add the page title as a title attribute to the menu link.
add_filter( 'page_menu_link_attributes', 'add_title_attribute_to_menu_link', 10, 5 ); function add_title_attribute_to_menu_link( $atts, $page, $depth, $args, $current_page_id ) { $atts['title'] = $page->post_title; return $atts; }