Adding an attribute and value to a WordPress Menu Item
Recently I had to add a Bootstrap modal trigger from a WordPress Menu item, the modal trigger requires an attribute of data-toggle with a value of modal. There is no facility to add this to a Menu Item in a menu in WP Dashboard, however their are 2 solutions on how this can be done.
Their is a filter available to add this nav_menu_link_attributes
add_filter( 'nav_menu_link_attributes', 'filter_function_name', 10, 3 ); function filter_function_name( $atts, $item, $args ) { // Manipulate attributes return $atts; }
In the Dashboard add in a Custom Link give it the modal link like href=”#MyModal”
Get the ID in the code using Web Inspector tools, add the ID as a variable, once that ID is matched add in the new attribute and value, in the case below data-toggle and modal
add_filter( 'nav_menu_link_attributes', 'themeprefix_menu_attribute_add', 10, 3 ); function themeprefix_menu_attribute_add( $atts, $item, $args ) { // Set the menu ID $menu_link = 1215; // Conditionally match the ID and add the attribute and value if ($item->ID == $menu_link) { $atts['data-toggle'] = 'modal'; } //Return the new attribute return $atts; }
jQuery Way
This is also achievable via jQuery
<script> jQuery(document).ready(function($){ $(".menu-item-1215").click(function(){ $("#myModal").modal('show'); }); }); </script>