据我所知,WordPress中的菜单处理程序使用菜单参数。你可以试着用这个。
使用参数过滤器,我们可以传递项的ID:
add_filter(
\'nav_menu_item_args\',
function( $args, $item, $depth ) {
$args->item_id = $item->ID;
return $args;
},
10,
3
);
然后在任何地方使用自定义参数。
add_filter(
\'walker_nav_menu_start_el\',
function($item_output, $item) {
if ( get_field( \'dropdown\', $item) == \'yes\' ) {
return \'<button aria-expanded="false" aria-controls="submenu-\'. $item->ID . \'" class="header__button">\' . $item->title . \'</button>\';
}
return $item_output;
},
10,
2
);
class My_Nav_Menu_Walker extends Walker_Nav_Menu {
/**
* Starts the list before the elements are added.
*
* @see Walker::start_lvl()
*
* @param string $output Used to append additional content (passed by reference).
* @param int $depth Depth of menu item. Used for padding.
* @param stdClass $args An object of wp_nav_menu() arguments.
*/
public function start_lvl( &$output, $depth = 0, $args = null ) {
if ( isset( $args->item_spacing ) && \'discard\' === $args->item_spacing ) {
$t = \'\';
$n = \'\';
} else {
$t = "\\t";
$n = "\\n";
}
$indent = str_repeat( $t, $depth );
// Default class.
$classes = array( \'sub-menu\' );
// ! Get parent item ID:
$id = isset( $args->item_id ) ? \' id="submenu-\' . absint( $args->item_id ) . \'"\' : \'\';
/**
* Filters the CSS class(es) applied to a menu list element.
*
* @since 4.8.0
*
* @param string[] $classes Array of the CSS classes that are applied to the menu `<ul>` element.
* @param stdClass $args An object of `wp_nav_menu()` arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$class_names = implode( \' \', apply_filters( \'nav_menu_submenu_css_class\', $classes, $args, $depth ) );
$class_names = $class_names ? \' class="\' . esc_attr( $class_names ) . \'"\' : \'\';
// ! Insert ID:
$output .= "{$n}{$indent}<ul{$class_names}{$id}>{$n}";
}
}
它仍然包括带有自定义Walker的文件,并将其指向菜单:
wp_nav_menu(
array(
\'container\' => false,
\'theme_location\' => \'primary\',
\'items_wrap\' => \'<ul class="header__nav-items header__nav-items--primary">%3$s</ul>\',
\'walker\' => new My_Nav_Menu_Walker()
)
);
我还没有测试代码。在某些情况下,可能存在冲突,您可以使用
clone
或使用另一种方法限制自定义参数的范围。