Written on 3. February 2020 by Lennart Christensen

How to add itemprop="url" and "name" data to a WordPress menu with php

Brief introduction to Google's structured data
Google's structured data is a form of markup that helps Google identify key information on your website that can be used for snippets in search results. So if you're a hotel, you can add data like identifying your average ratings and price ranges so Google can use that information to create a better search result.

This blog post is about how you can add Google structured data / Schema markup (SiteNavigationElement) to your WordPress navigation menu "wp_nav_menu". The post is aimed primarily at those who have some knowledge of programming WordPress themes 🤓

The challenge with WordPress menu and adding schema data
The WordPress menu is output in html by a function, so what do you do if you want to add schema data to the content where we include itemprop="url" and "name".

Your WordPress navigation menu function probably looks similar to this:

wp_nav_menu(array('theme_location' => 'primary', 'menu_class' => 'cco_menu'));

The solution 🔨🔨
Wrap the menu function that spits out the navigation menu with a div element to refer to "SiteNavigationElement" and extend the WordPress function to wrap the menu li with a span containing itemprop="name".

Like this:

<div class=""  itemscope="itemscope" itemtype="http://schema.org/SiteNavigationElement">									  
wp_nav_menu(array('theme_location' =&gt; 'primary', 'menu_class' =&gt; 'ms_menu', 'before' =&gt; '', 'after' =&gt; '')); 

Then add the following filter to your functions.php file:

function add_menu_attributes( $atts, $item, $args ) {
  $atts['itemprop'] = 'url';
  return $atts;
add_filter( 'nav_menu_link_attributes', 'add_menu_attributes', 10, 3 );

That's it! 🙌

Some reading/info about Schema and WordPress filters:

More background reading on Google's Structured Schema data can be found here: