As the formal enclosure for menu items is the <menu>
tag how to I make WordPress use the <menu>
tag as a wrapper around menu items instead of the more generic <ul>
?
EDIT: I believe this is what I'm aiming at and this appears to be a solution.
As the formal enclosure for menu items is the <menu>
tag how to I make WordPress use the <menu>
tag as a wrapper around menu items instead of the more generic <ul>
?
EDIT: I believe this is what I'm aiming at and this appears to be a solution.
To make WordPress use the tag instead of for wrapping menu items, you can customize the output of wp_nav_menu() using the wp_nav_menu_args filter. Here's how you can do it:
Solution: Modify the Menu Container You can achieve this by adding the following code to your theme’s functions.php file:
function use_menu_tag_as_wrapper($args) {
// Set the container to 'menu'
$args['container'] = 'menu';
// Remove the default class added by WordPress (optional)
$args['container_class'] = '';
return $args;
}
add_filter('wp_nav_menu_args', 'use_menu_tag_as_wrapper');
If you're just trying to replace <ul...>
and </ul>
with <menu...>
and </menu>
in the generated HTML, you can use the wp_nav_menu
filter:
add_filter( 'wp_nav_menu', 'wpse_426932_menu_fix' );
/**
* Fixes the menu HTML to use <menu> instead of <ul>.
*
* @param string $html The menu HTML.
* @return string The fixed menu HTML.
*/
function wpcs_426932_menu_fix( $html ) {
$html = str_replace(
array( '<ul', '</ul>' ),
array( '<menu', '</menu>' ),
$html
);
return $html;
}
You can add this code to your active theme's functions.php
file or you can make it into a simple plugin. (I tend to prefer the plugin route, because that way it keeps on working even if you change themes.)
Note: This is a very simple string replacement. If you need something more complex, you might need to use preg_replace()
.
menu
is not a list of navigation links. It's for application menus, like the File menu. Notice how all the examples on MDN use<button>
elements, not links. The semantically correct approach for a navigation menu is to wrap the list with a<nav>
. – Jacob Peattie Commented Sep 27, 2024 at 18:08<nav>
is the correct element. – Jacob Peattie Commented Sep 29, 2024 at 12:15