I'm Twitter Bootstrap and need to add data-toggle="modal" attribute to the a tag of menu link. Upon searching most all results reference doing a walking for Twitter Bootstrap dropdown menus however this menu has no dropdowns and I only need to add the particular attribute.
Next I found this: Add custom attributes to menu items without plugin which is very helpful as it appears in WordPress 3.6+ we no longer have to do long complex walkers and instead can use this: http://codex.wordpress.org/Plugin_API/Filter_Reference/nav_menu_link_attributes
However as of this running that API reference is quite bare and offers no examples and since it's so new there are very few references to it on Google.
I tried this first:
add_filter( 'nav_menu_link_attributes', 'mywp_contact_menu_atts', 10, 3 );
function pb_contact_menu_atts( $atts, $item, $args )
{
// inspect $item, then …
$atts['data-toggle'] = 'modal';
return $atts;
}
and that does work however it as expected adds the attribute to all the a tags in the menu. So I'm trying to figure out how to target one menu item with #menu-item-7857 a or such.
Does anyone know where to find an example of targeting a menu item or able to determine how to basd on the information that's in the above linked API reference?
To note, I did find the following one example but it only targets items that have children which does not help but may be in the right direction:
add_filter('nav_menu_link_attributes', function($atts, $item, $args) {
if ( $args->has_children )
{
$atts['data-toggle'] = 'dropdown';
$atts['class'] = 'dropdown-toggle';
}
return $atts;
}, 10, 3);
UPDATE - The only answer below sounds like it's on to something but from it wasn't able to determine how to actually find the number to target my specific link and where/how to add that conditional in a working example. Added a comment but didn't hear back. Since been about 18 days thought I'd see if a bounty would help.
When I look at the code for the link I want to target:
<li id="menu-item-7858" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-7858"><a href="#" data-toggle="modal">Chat</a></li>
I see the number 7858 so thinking maybe that is the number I should be targeting.
But when I try for instance:
add_filter( 'nav_menu_link_attributes', 'my_chat_menu_atts', 10, 3 );
function my_chat_menu_atts( $atts, $item, $args ) {
if ( 7857 == $item['ID'] ) {
// inspect $item, then …
$atts['onclick'] = 'SnapEngage.startLink();';
return $atts;
}
}
However adding that if statement the one commenter suggested I get the following error:
Fatal error: Cannot use object of type WP_Post as array
I'm assuming more code is required but at a lost. As a reminder without the if statement it works however it targets all links rather than the one link I want to target.