这只是一种PHP快捷方式,但您可以创建一个映射,描述哪些条件值映射到哪些菜单位置,并在其中循环测试每个条件并打印匹配的菜单:
/**
* Prints wp_nav_menu(s) by matching conditional function arguments to menu locations.
*
* @param array $locations A mapping of predicate function names to associative
* arrays mapping predicate function arguments to menu
* locations.
* @param array $args Optional. An associative array of arguments to pass on to
* wp_nav_menu().
* @param boolean $multiple Optional. Whether or not to allow multiple menus to
* match/print.
* @return string|void The menu(s) markup, if $args[\'echo\'] is set to false.
**/
wpse390599_conditional_nav_menu( $locations, $args = [], $multiple = false ) {
$conditional_locations = $locations;
$markup = \'\';
$return = isset( $args[\'echo\'] ) && $args[\'echo\'] === false;
foreach( $conditional_locations as $predicate => $locations ) {
foreach( $locations as $condition => $location ) {
if( ! call_user_func( $predicate, $condition ) )
continue; // No match - skip location.
// Predicate conditional returned TRUE - print the menu
$args[\'location\'] = $location;
$markup = wp_nav_menu( $args );
// If we\'re not facilitating multiple matching menus, bail out.
if( ! $multiple ) {
// Return the markup if `$args[\'echo\'] is false, per wp_nav_menu() convention.
if( $return )
return $markup;
return;
}
}
}
// If multiple menus were matched and $args[\'echo\'] is false, return the markup.
if( $return )
return $markup;
}
用法:
wpse390599_conditional_nav_menu(
[
\'is_page\' => [
\'page-1\' => \'secondary-menu-1\',
\'page-2\' => \'secondary-menu-2\',
\'\' => \'secondary-menu-default\',
],
]
);
作为额外的好处,当
$multiple
是
false
, 的排序
$conditional_locations
在多个条件匹配的情况下,可以使用数组指定优先级。
这是否比您当前的解决方案更易于维护,实际上取决于用例的具体情况。注意,此结构不支持采用多个参数的WordPress条件谓词,例如。is_tax( $taxonomy, $term )
.