Conditional secondary menus

时间:2021-06-15 作者:Vinz Clortho

我有一个由3个项目组成的主菜单,每个项目都有一个不同的辅助菜单。我想在每个页面上显示相关的二级菜单。我目前使用的是带有slug的is\\u页面。我需要添加wpml,这样每个页面都会有更多的slug。我想问一下,您是否可以建议我一个更干净、更易于维护的解决方案。这就是我当时所做的:

if ( is_page( \'page-1\' ) ) {
  wp_nav_menu(
   array(
     \'theme_location\' => \'secondary-menu-1\'
   )
  );
} elseif (is_page( \'page-2\' ) ) {
  wp_nav_menu(
    array(
      \'theme_location\' => \'secondary-menu-2\'
     )
  );
}

1 个回复
最合适的回答,由SO网友:bosco 整理而成

这只是一种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\',
     ],
  ]
);
作为额外的好处,当$multiplefalse, 的排序$conditional_locations 在多个条件匹配的情况下,可以使用数组指定优先级。

这是否比您当前的解决方案更易于维护,实际上取决于用例的具体情况。注意,此结构不支持采用多个参数的WordPress条件谓词,例如。is_tax( $taxonomy, $term ).