Thanks, smutek, but I don’t think that’s what I was asking… or at least what I meant to ask…
We’re able to extend the built-in WordPress class. What we’re wanting to do is extend the Soil NavWalker class, which is what you referenced. We like that class but it’s missing the schema markup.
We would think we could use:
use Roots\Soil\Nav\NavWalker;
at the top of our helpers.php file, but it doesn’t seem to work. What we ended up doing (which may or may not be the best way of getting it done, but it worked… ) is;
At the top of the /src/helpers.php file, we require_once the nav-walker.php module from the soil plugin:
require_once(WP_PLUGIN_DIR . '/soil/modules/nav-walker.php');
Then we write out our own custom class adding the schema markup by extending the Soil NavWalker class:
class Add_Schema_Markup_To_Menu extends \Roots\Soil\Nav\NavWalker {
var $db_fields = array(
'parent' => 'menu_item_parent',
'id' => 'db_id'
);
function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
$classes = apply_filters('nav_menu_css_class', [], $item);
$output .= sprintf( "\n<li itemprop=\"name\" %s><a itemprop=\"url\" href='%s'>%s</a>\n",
empty( $classes ) ? array() : 'class="' . implode($classes, ' ') .'"',
$item->url,
$item->title
);
}
function end_el( &$output, $object, $depth = 0, $args = array() ) {
$output .= '</li>';
}
}
We had to extend Soil’s NavWalker class rather than the built in WordPress class because we wanted to maintain the cleaner navigation menus that soil provides but we need to override the ‘start_el’ function so that we could add our schema to the li and a elements.
This is now what it looks like when we call the menu:
wp_nav_menu(['theme_location' => 'primary_navigation', 'menu_id' => 'desktop-menu', 'menu_class' => 'nav', 'items_wrap' => '<ul itemscope itemtype="http://schema.org/SiteNavigationElement" id="%1$s" class="%2$s">%3$s</ul>', 'walker' => new App\Add_Schema_Markup_To_Menu()])
This seems a little clunky, but it works.
The main question at this point is, how should we have autoloaded or included Soil’s NavWalker class into our helpers file so that we could extend it?