I’ve followed the documentation for this and am able to add custom fields to IDs, titles, and classes. However, what I’m trying to do is add a data attribute to the <li>
menu item. I’m currently returning the following:
<li id="data-menuanchor="#secondSection">
but what I need is this instead:
<li data-menuanchor="$secondSection">.
Here is the current code I have:
add_filter('wp_nav_menu_objects', 'my_wp_nav_menu_objects', 10, 2);
function my_wp_nav_menu_objects( $items, $args ) {
// loop
foreach( $items as &$item ) {
// vars
$datamenuanchor = get_field('data-menuanchor', $item);
// append icon
if( $datamenuanchor ) {
$item->ID.= ' data-anchor="'.$datamenuanchor.'"';
}
}
// return
return $items;
}
It is not possible to add attributes to the li by altering the ID. Normally you could try this
$item->ID.= '" data-anchor="'.$datamenuanchor;
but that will not work because of the esc_attr() function where the value of $id is used
$id = $id ? ' id="' . esc_attr( $id ) . '"' : '';
$output .= $indent . '<li' . $id . $class_names . '>';
I’m pretty sure that to add this data attributes to the li’s that you’ll need to create a custom nave walker.