WordPress – How to add Google Structured Data to navigation menus

This article is aimed at those who have some knowledge of programming WordPress themes and is specifically about adding structured data to WordPress navigation menus.

Navigation menus in WordPress are generated by a function.  You may need to manipulate the function to structure how navigation menus are rendered.

For instance, your site’s navigation menu may be generated with PHP code in your theme like this:

wp_nav_menu(['theme_location' => 'primary_navigation', 'walker' => MyNavWalker(), 'menu_class' => 'nav']);

This would result in the following output being generated:

<nav id="access">
  <div class="menu-menu-1-container">
    <ul id="menu-main">
      <li class="menu-main">
        <a href="http://mywebsite.com/">Home</a>
      </li>
      <li class="menu-about">
        <a href="http://mywebsite.com/about">About</a>
      <li>
      <li class="menu-blog">
        <a href="http://mywebsite.com/blog">Blog</a>
      </li>
    </ul>
  </div>
</nav>

Problem

However, for Google Page Ranking algorithms to properly detect the navigation menu as a Site Navigation Element containing one or more child elements you want the output for your site navigation menu to be like this:

<nav id="access" itemscope="itemscope" itemtype="http://schema.org/SiteNavigationElement">
  <div class="menu-menu-1-container">
    <ul id="menu-main">
      <li class="menu-main">
        <a itemprop="url" href="http://mywebsite.com/">Home</a>
      </li>
      <li class="menu-about">
        <a itemprop="url" href="http://mywebsite.com/about">About</a>
      <li>
      <li class="menu-blog">
        <a itemprop="url" href="http://mywebsite.com/blog">Blog</a>
      </li>
    </ul>
  </div>
</nav>

Solution

First, wrap your wp_nav_menu function in a span or nav element to reference the site navigation element schema like so:

<nav id="access" itemscope="itemscope" itemtype="http://schema.org/SiteNavigationElement">
  wp_nav_menu(['theme_location' => 'primary_navigation', 'walker' => MyNavWalker(), 'menu_class' => 'nav']);
</nav>

To inject the itemprop=”url” tags we need to edit functions.php and introduce a custom function like so:

function add_menu_attributes( $atts, $item, $args ) {
  $atts['itemprop'] = 'url';
  return $atts;
}
add_filter( 'nav_menu_link_attributes', 'add_menu_attributes', 10, 3 );
WordPress – How to add Google Structured Data to navigation menus was last modified: June 15th, 2015 by tabcom