Skip to content

Instantly share code, notes, and snippets.

@shrinkray
Created December 22, 2019 03:13
Show Gist options
  • Save shrinkray/0e6bcaf800f0cc694bd5816fccea7fe1 to your computer and use it in GitHub Desktop.
Save shrinkray/0e6bcaf800f0cc694bd5816fccea7fe1 to your computer and use it in GitHub Desktop.
Add a data attribute of page/post to a WordPress Menu ( wp_nav_menu() )
/**
* Add a data attribute of page/post to a WordPress Menu
* Add this to your functions.php file
*
* This function will add the page/post ID of item the menu links to
* when using wp_nav_menu(); to build the menu.
*
* Example:
*
* <li id="menu-item-28" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-28">
* <a href="http://mysite.dev/my-page/" data-id="9">My Page</a>
* </li>
*
* @link https://developer.wordpress.org/reference/functions/wp_nav_menu/
* @link https://developer.wordpress.org/reference/functions/get_post_meta/
*/
add_filter( 'nav_menu_link_attributes', 'tmg__menu_atts', 10, 3 );
function tmg__menu_atts( $atts, $item, $args )
{
$atts['data-id'] = get_post_meta( $item->ID, '_menu_item_object_id', true );
return $atts;
}
@shrinkray
Copy link
Author

shrinkray commented Dec 22, 2019

This was the perfect filter to use with the Root Inc site, converting their navigation data attributes, including anchor class to be used in the WordPress wp_nav_menu() function. It will save time in changing the configuration of using the hard coded data attributes. I do not need this to get the ID but will use it to manipulate other keys for the post meta of the link.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment